<?php
            
use app\model\Util; 
use app\model\Theme; 


/**
 * Desc:
 * Time: 2021/6/25 11:26
 * author: wsx
 */
class Index_Page extends PluginWebPage {
    //店铺设置页面,店铺添加、修改信息
    function main() {
        $method = 'shopplan_main';
        global $_G,$_P,$_S,$_C;
        $system = $_S;
        //themeid相当于商家id，有唯一性
        $themeid = intval($_P['themeid']);

        if($themeid <= 0){
            $themeid = Theme::getDefaultThemenew();
        }
        $theme = Theme::getThemeById($themeid);
        $themelist = Theme::getAllTheme();
        if(empty($theme['id'])){
            return_msg('还没有创建活动,请联系管理员');
        }

        $storeid = $_P['storeid']?intval($_P['storeid']):$themeid;

        $themelist = Theme::getAllTheme();
        //获取id（某商家）的店铺配置信息
        if ($storeid){
            $item = ShopplanModel::getConfigByStoreId($storeid);
        }
        //判断规划类表
        $total = ShopplanModel::getSpecialWorkTimesListTotal($storeid);
        if (!$total){
            //默认数据
            $work_rules =[
                ['worktimes'=>'08:30','nums'=>1,'ages_start'=>0,'ages_end'=>1200,'id'=>''],
                ['worktimes'=>'10:30','nums'=>1,'ages_start'=>0,'ages_end'=>1200,'id'=>''],
                ['worktimes'=>'13:30','nums'=>1,'ages_start'=>0,'ages_end'=>1200,'id'=>''],
                ['worktimes'=>'15:30','nums'=>1,'ages_start'=>0,'ages_end'=>1200,'id'=>''],
            ];
            //整理入库数据
            $data = [
                'plantimeid'    =>0,                  //分店时间配置表id
                'storeid'       =>$storeid,                     //店铺id
                'tplname'       =>'默认',                     //规划名称
                's_work_rules'  =>json_encode($work_rules),     //本规划规则
                'totalnums'     =>4,                   //当天可预约客户总数（本规划）
                'status'        =>1,                            //规划状态，1，默认开启，0为关闭
                // 'agelimit'      =>$agelimit,                    //年龄限制，0，默认关闭，1为开启
                'updated_at'    =>date("Y-m-d H:i:s"),
            ];
            //入库
            $insert_id = ShopplanModel::insertSpecialWorktimes($data);
        }

        $addsum=0;
        if (!empty($item) && $item) {
            $item['start_date'] = strtotime($item['start_date']);
            $item['end_date'] = strtotime($item['end_date']);
            $id=$item['id'];
            $shopconfig=json_decode($item['shopconfig'],TRUE);
            //找出最大的shopid来,新增分店的shopid必须大于“原最大shopid”
            $maxshopid=0;
            foreach ($shopconfig as $k => $v) {
                if ($v['shopid'] > $maxshopid) {
                    $maxshopid =$v['shopid'];
                }
            }
            $sumshopid=count($shopconfig);
            
            if ($maxshopid > ($sumshopid-1)) {
                $addsum = $maxshopid+1-$sumshopid;
            }

            $shops=array_shift($shopconfig);//$shops是总店数据，$shopconfig是分店数据（已抛出总店）

        }else{
            $shopinfos[0]['name']       = $_C['jubf'];
            $shopinfos[0]['address']    = $_C['province'].$_C['city'].$_C['district'].$_C['addresstxt'];
            $shopinfos[0]['phone']      = $_C['mobile'];
            $shopinfos[0]['like']       = 1;
            $shopinfos[0]['shopid']     = 1;
            $shopinfos[0]['logo']       ='';

            $data = [
                'storeid'       =>$storeid,//商家id的模拟数据
                'shopconfig'    =>json_encode($shopinfos),
                'plantext'      =>'立即预约',
                'planedtext'    =>'查看预约',
                'enable_days'   =>7,
                'days_away'     =>3,
                'max_edit_nums' =>5,
                'agelimit'      =>0,
                'start_date'      =>$theme['begintime'],
                'end_date'      =>$theme['endtime'],
                'updated_at'    =>date("Y-m-d H:i:s"),
            ];

            $res = ShopplanModel::insertConfig($data);
            if (!$res){
                return_tips('操作失败', $url, 'error');
            }else{
                return_tips('操作成功，请设置时间规划！',webUrl('shopplan',array('id'=>$id,'themeid'=>$themeid)), 'success');
            }
        }

        if ($_G['ispost']) {
            //获取post来的分店配置信息
            $id      = intval($_P['id']);
            $storeid = $_P['storeid']?intval($_P['storeid']):$themeid;
            $plantext =trim($_P['plantext']);//预约前，按钮文字，比如“立刻预约”
            $planedtext =trim($_P['planedtext']);//预约后，按钮文字，比如“查看预约”
            $enable_days =intval(trim($_P['enable_days']));//客户预约后，多少天内可以修改
            $days_away =intval(trim($_P['days_away']));//距离已经预约大家都在发大家都在发大家都在发的日期，多少天外可以修改
            $max_edit_nums =intval(trim($_P['max_edit_nums']));//最大修改次数
            $agelimit =intval(trim($_P['agelimit']));//年龄限制
            $start_date = $_P['shopplan_date']['start'];//活动结束日期
            $end_date = $_P['shopplan_date']['end'];//活动结束日期

            if($enable_days<0){
                return_tips('最长可改时间不能为负数', $url, 'error');
            }
            if($days_away<0){
                return_tips('最晚修改日期不能为负数', $url, 'error');
            }
            if($max_edit_nums<0){
                return_tips('最大修改次数不能为负数', $url, 'error');
            }

            $data = [
                'storeid'       =>$storeid,//商家id的模拟数据
                // 'shopconfig'    =>json_encode($shopinfos),
                'plantext'      =>$plantext,
                'planedtext'    =>$planedtext,
                'enable_days'   =>$enable_days,
                'days_away'     =>$days_away,
                'max_edit_nums' =>$max_edit_nums,
                'agelimit'      =>$agelimit,
                'start_date'      =>$start_date,
                'end_date'      =>$end_date,
                'updated_at'    =>date("Y-m-d H:i:s"),
            ];

            $where = ['id'=>$id];
            $res = ShopplanModel::editConfigByWhere($where,$data);
            if (!$res){
                return_tips('操作失败', $url, 'error');
            }else{
                return_tips('操作成功',webUrl('shopplan',array('id'=>$id,'themeid'=>$themeid)), 'success');
            }
        }
        $return_clicent = get_defined_vars();
return $this->view('/shopplan/main', $return_clicent);
    }
    //店铺设置页面,店铺添加、修改信息
    function shops() {
        $method = 'shopplan_shops';
        global $_G,$_P,$_S,$_C;
        $system = $_S;
        //themeid相当于商家id，有唯一性
        $themeid = intval($_P['themeid']);

        if($themeid <= 0){
            $themeid = Theme::getDefaultThemenew();
        }
        $theme = Theme::getThemeById($themeid);
        $themelist = Theme::getAllTheme();
        if(empty($theme['id'])){
            return_msg('还没有创建活动,请联系管理员');
        }

        $storeid = $_P['storeid']?intval($_P['storeid']):$themeid;
        $tomorrow = date('Y-m-d',(time()+86400));
        //获取id（某商家）的店铺配置信息
        if ($storeid){
            $item = ShopplanModel::getConfigByStoreId($storeid);
            //获取店铺（storeid或者themeid）的所有规划信息
            $tplitem = ShopplanModel::getSpecialWorktimesListByStoreid($storeid);
        }

        $addsum=0;
        if (!empty($item)) {
            $id=$item['id'];
            $shopconfig=json_decode($item['shopconfig'],TRUE);
            //找出最大的shopid来,新增分店的shopid必须大于“原最大shopid”
            $maxshopid=0;
            foreach ($shopconfig as $k => $v) {
                if ($v['shopid'] > $maxshopid) {
                    $maxshopid =$v['shopid'];
                }
            }
            $sumshopid=count($shopconfig);
            
            if ($maxshopid > $sumshopid) {
                $addsum = $maxshopid-$sumshopid;
            }
            $shops=array_shift($shopconfig);//$shops是总店数据，$shopconfig是分店数据（已抛出总店）

        }else{
            $shopinfos[0]['name']       = $_C['jubf'];
            $shopinfos[0]['address']    = $_C['province'].$_C['city'].$_C['district'].$_C['addresstxt'];
            $shopinfos[0]['phone']      = $_C['mobile'];
            $shopinfos[0]['like']       = 1;
            $shopinfos[0]['shopid']     = 1;
            $shopinfos[0]['logo']       ='';

            $data = [
                'storeid'       =>$storeid,//商家id的模拟数据
                'shopconfig'    =>json_encode($shopinfos),
                'plantext'      =>'立即预约',
                'planedtext'    =>'查看预约',
                'enable_days'   =>7,
                'days_away'     =>3,
                'max_edit_nums' =>5,
                'agelimit'      =>0,
                'start_date'      =>$theme['begintime'],
                'end_date'      =>$theme['endtime'],
                'updated_at'    =>date("Y-m-d H:i:s"),
            ];

            $res = ShopplanModel::insertConfig($data);
            if ($res){
                $shop_id = $res;
                //判断规划类表
                $total = ShopplanModel::getSpecialWorkTimesListTotal($storeid);
                if (!$total){
                    //默认数据
                    $work_rules =[];
                }
                //判断门店规划

            }
            if (!$res){
                return_tips('操作失败', $url, 'error');
            }else{
                return_tips('操作成功，请设置时间规划！',webUrl('shopplan.shops',array('id'=>$id,'themeid'=>$themeid)), 'success');
            }
        }
        if ($_G['ispost']) {

            //获取post来的分店配置信息
            $id      = intval($_P['id']);
            $storeid = intval($_P['storeid']);
            $shopinfos=$_P['infos'];
            sort($shopinfos);


            if (!empty($shopinfos)) {

                //防止空数据入库
                foreach ($shopinfos as $key => $shopvalue) {
                    if (empty($shopinfos[0]['name'])) {
                        return_tips('主店名称不能为空', $url, 'error');
                    }elseif (empty($shopinfos[0]['address'])) {
                        return_tips('主店地址不能为空', $url, 'error');
                    }elseif (empty($shopinfos[0]['phone'])) {
                        return_tips('主店电话不能为空', $url, 'error');
                    }elseif ($key !== 0 && empty($shopinfos[$key]['name'])) {
                        return_tips($key.'分店名称不能为空', $url, 'error');
                    }elseif ($key !== 0 && empty($shopinfos[$key]['address'])) {
                        return_tips($key.'分店地址不能为空', $url, 'error');
                    }elseif ($key !== 0 && empty($shopinfos[$key]['phone'])) {
                        return_tips($key.'分店电话不能为空', $url, 'error');
                    }else{

                        //对分店数组按照shopid排序
                        foreach($shopinfos as $val){
                            $key_arrays[]=$val['shopid'];
                        }
                        array_multisort($key_arrays,SORT_ASC,SORT_NUMERIC,$shopinfos);
                        //分店按照shopid排序结束

                        if(empty($id)){
                            $shopinfos[$key]['shopid']  =$key;
                        }else{
                            $shopinfos[$key]['shopid']  =$shopinfos[$key]['shopid'];

                            //logo值保持不变
                            $shopconfig=json_decode($item['shopconfig'],TRUE);
                            foreach($shopconfig as $index => $value){
                                if ($shopinfos[$key]['shopid'] == $value['shopid']) {
                                    $shopinfos[$key]['logo'] = $value['logo'];
                                }
                            }
                        }
                        $shopinfos[$key]['name']    =trim($shopinfos[$key]['name']);
                        $shopinfos[$key]['address'] =trim($shopinfos[$key]['address']);
                        $shopinfos[$key]['phone']   =trim($shopinfos[$key]['phone']);
                        $shopinfos[$key]['like']    =trim($shopinfos[$key]['like']);


                    }
                }

                $data = [
                    'storeid'       =>$storeid,//商家id的模拟数据
                    'shopconfig'    =>json_encode($shopinfos),
                    'updated_at'    =>date("Y-m-d H:i:s"),
                ];

                $where = ['id'=>$id];
                $res = ShopplanModel::editConfigByWhere($where,$data);
                if (!$res){
                    return_tips('操作失败', $url, 'error');
                }else{
                    return_tips('操作成功',webUrl('shopplan.shops',array('id'=>$id,'themeid'=>$themeid)), 'success');
                }
            }
        }
        $return_clicent = get_defined_vars();
return $this->view('/shopplan/shops', $return_clicent);
    }
    //单一门店信息修改
    function editshop(){
        global $_G,$_P,$_S,$_C;
        $system = $_S;
        $themeid = intval($_P['themeid']);
        $storeid = $_P['storeid']?intval($_P['storeid']):$themeid;

        //获取id（某商家）的店铺配置信息
        if ($storeid){
            $item = ShopplanModel::getConfigByStoreId($storeid);
        }
        if (!empty($item)) {
            $id=$item['id'];
            $shopconfig=json_decode($item['shopconfig'],TRUE);
        }

        $shopid = intval($_P['shopid']);
        $name = trim($_P['name']);
        $address = trim($_P['address']);
        $phone = trim($_P['phone']);
        $like = intval($_P['like']);

        $temp_shop['shopid'] = $shopid;
        $temp_shop['name'] = $name;
        $temp_shop['address'] = $address;
        $temp_shop['phone'] = $phone;
        $temp_shop['like'] = $like;
        //防止空数据入库
        foreach ($shopconfig as $key => $shopvalue) {
            if (empty($name)) {
                show_json(0,['msg'=>'门店名称不能为空！']);
            }elseif (empty($address)) {
                show_json(0,['msg'=>'门店地址不能为空！']);
            }elseif (empty($phone)) {
                show_json(0,['msg'=>'门店电话不能为空']);
            }else{

                //对分店数组按照shopid排序
                // foreach($shopconfig as $val){
                //     $key_arrays[]=$val['shopid'];
                // }
                // array_multisort($key_arrays,SORT_ASC,SORT_NUMERIC,$shopinfos);
                //分店按照shopid排序结束

                if ($shopconfig[$key]['shopid'] == $shopid) {
                    $shopconfig[$key]['shopid']  = $shopid;
                    $shopconfig[$key]['name']    =$name;
                    $shopconfig[$key]['address'] =$address;
                    $shopconfig[$key]['phone']   =$phone;
                    $shopconfig[$key]['like']    =$like;
                }elseif ($shopid > count($shopconfig)) {
                    $shopconfig[] = $temp_shop;
                }

            }
        }

        if ($_G['ispost']) {

            $data = [
                'storeid'       =>$storeid,//商家id的模拟数据
                'shopconfig'    =>json_encode($shopconfig),//更新门店信息
                'updated_at'    =>date("Y-m-d H:i:s"),
            ];

            $where = ['id'=>$id];
            $res = ShopplanModel::editConfigByWhere($where,$data);

            if ($res){
                show_json(1,['msg'=>'操作成功']);
            }else{
                show_json(0,['msg'=>'操作失败']);
            }
        }
    }
    /*
    //门店年龄限制
    function mainagelimit(){
        global $_G,$_P,$_S,$_C;
        $system = $_S;
        $themeid = intval($_P['themeid']);
        $storeid = $_P['storeid']?intval($_P['storeid']):$themeid;

        //获取id（某商家）的店铺配置信息
        if ($storeid){
            $item = ShopplanModel::getConfigByStoreId($storeid);
        }
        if (!empty($item)) {
            $id=$item['id'];
        }

        $agelimit = intval($_P['agelimit']);

        if ($agelimit==1) {
            $mainagelimit = 0;
        }elseif ($agelimit==0) {
            $mainagelimit = 1;
        }

        if ($_G['ispost']) {

            $data = [
                'storeid'       =>$storeid,//商家id的模拟数据
                'agelimit'      =>$mainagelimit,//年龄限制
                'updated_at'    =>date("Y-m-d H:i:s"),
            ];

            $where = ['id'=>$id];
            $res = ShopplanModel::editConfigByWhere($where,$data);

            if ($res){
                show_json(1,['msg'=>'操作成功']);
            }else{
                show_json(0,['msg'=>'操作失败']);
            }
        }
    }
    //添加、编辑分店logo
    function editlogo(){
        global $_G,$_P,$_S,$_C;
        $system = $_S;
        $method = 'shopplan_editlogo';
        $themeid = intval($_P['themeid']);
        $storeid = $_P['storeid']?intval($_P['storeid']):$themeid;
        $shopid = isset($_P['shopid'])?$_P['shopid']:'1';
        //获取id（某商家）的店铺配置信息
        if ($storeid){
            $item = ShopplanModel::getConfigByStoreId($storeid);
        }

        if (!empty($item)) {
            $id=$item['id'];
            $shopconfig=json_decode($item['shopconfig'],TRUE);

            foreach ($shopconfig as $k => $v) {
                if ($v['shopid'] == $shopid) {
                    $shops = $v;
                }
            }
        }


        if ($_G['ispost']) {

            $logo = $_P['logo'];
            if (empty($logo)) {
                return_tips('请上传分店LOGO图片！', $url, 'error');
            }

            foreach ($shopconfig as $k => $v) {
                if ($v['shopid'] == $shopid) {
                    $shopconfig[$k]['logo'] = $logo;
                }
            }

            $data = [
                'storeid'       =>$storeid,//商家id的模拟数据
                'shopconfig'    =>json_encode($shopconfig),
                'updated_at'    =>date("Y-m-d H:i:s"),
            ];


            $where = ['id'=>$id];
            $res = ShopplanModel::editConfigByWhere($where,$data);

            if (!$res){
                return_tips('操作失败', $url, 'error');
            }else{
                return_tips('操作成功',webUrl('shopplan.editlogo',array('shopid'=>$shopid,'themeid'=>$themeid)), 'success');
            }

        }

        $return_clicent = get_defined_vars();
return $this->view('/shopplan/editlogo', $return_clicent);
    }*/
    //每周日期管理
    function setplan() {
        global $_G,$_P,$_S,$_C;
        $system = $_S;
        $method = 'shopplan_setplan';
        $navtabs= 'shopplan_setplan';

        //获取商家id+分店id
        $themeid = intval($_P['themeid']);
        $storeid=$_P['themeid']?$_P['themeid']:$_P['storeid'];//themeid相当于storeid
        $shopid =$_P['shopid']?$_P['shopid']:'1';

        if ($storeid) {
            $item = ShopplanModel::getConfigByStoreId($storeid);
        }

        //如果有分店时间配置表id，或者有（商家id+店铺id），获取原来配置信息
        if ($storeid && $shopid >= 1) {
            $item = ShopplanModel::getTimeConfigByStoreId($storeid,$shopid);
        }

        $id=$item['id'];//获取分店时间配置表的id

        //没有时间配置id的店铺，去存取一个
        if (!$id) {
            //取出默认的规划
            $default_item = ShopplanModel::getDefaultSpecialWorkTimeItem($storeid,'默认');
            if ($default_item){
                $item_id = $default_item['id'];
                $tplweek = [];
                $tplweek['week01'] = 'holiday';
                $tplweek['week02'] = $item_id;
                $tplweek['week03'] = $item_id;
                $tplweek['week04'] = $item_id;
                $tplweek['week05'] = $item_id;
                $tplweek['week06'] = $item_id;
                $tplweek['week07'] = $item_id;
               // $tplweek['week06'] = 'holiday';
               // $tplweek['week07'] = 'holiday';
            }
            $data = [
                'storeid'       =>$themeid,                         //商家id的模拟数据
                'shopid'        =>$shopid,                          //店铺id的模拟数据
                'workdays'      =>json_encode($tplweek),            //每周时间规划
                'special_rules' =>json_encode($plan_s_work00_time), //特殊日期（日期+规划）
                'updated_at'    =>date("Y-m-d H:i:s"),
            ];

            $res = ShopplanModel::insertTimeConfig($data);
            $id = $res;
        }

        //获取店铺（storeid或者themeid）的所有规划信息
        $tplitem = ShopplanModel::getSpecialWorktimesListByStoreid($storeid);

        // if (empty($tplitem)) {
        //     return_tips('请添加时间规划', createWebUrlPlugin('shopplan.setspecial',array('themeid'=>$themeid,'plantimeid'=>$id,'shopname'=>$shopname,'shopid'=>$shopid)), 'success');
        // }
        $item = ShopplanModel::getTimeConfigByStoreId($storeid,$shopid);
        //每周几使用的规划
        $week_w=json_decode($item['workdays'],TRUE);

        //获取时间段+时间段的数量
        if (!empty($week_w)) {
            foreach ($week_w as $week_w_key => $week_w_value) {
                if ($week_w_value != 'holiday') {
                    $tplinfo = ShopplanModel::getSpecialWorktimesById($week_w_value);
                    $week_temp =json_decode($tplinfo['s_work_rules'],TRUE); 
                    foreach ($week_temp as $key => $value) {
                        $weekinfo[$week_w_key][$key] = $value["worktimes"];
                        $weeknums[$week_w_key][$key] = $value["nums"];
                    }
                }else{
                    $weekinfo[$week_w_key][0]='休息日';
                    $weeknums[$week_w_key][0] = 0;
                }
            }
        }

        //拼接一个前端的form表格
        $plan='<form id="form2"  action="{php echo createWebUrlPlugin(\'shopplan.setplan\',array(\'id\'=>$id,\'themeid\'=>$themeid,\'shopid\'=>$shopid));}" enctype ="multipart/form-data" method="post">'.PHP_EOL;
        $plan.='<div class="panel panel-default" role="tabpanel" style="">'.PHP_EOL;
        $plan.='<div class="panel-heading" >门店规划 <a href="javascript:isShowPlan(false)" style="float: right;">关闭</a></div>'.PHP_EOL;
        $plan.='<div class="panel-body" style="">'.PHP_EOL;
        $plan.='<div class="form-group">'.PHP_EOL;
        $plan.='<label class="col-xs-12 col-sm-3 col-md-2 control-label"></label>'.PHP_EOL;
        $plan.='<div class="col-sm-12 col-xs-12">'.PHP_EOL;
        $plan.='<label class="col-sm-3 col-xs-12 control-label"><span style="color: red;">*</span>周一时间规划</label>'.PHP_EOL;
        $plan.='<div class="col-sm-4">'.PHP_EOL;
        $plan.='<select name="week01">'.PHP_EOL;
        $plan.='<option disabled selected>请选择</option>'.PHP_EOL;
        $plan.='<option value="holiday"';
        if($week_w['week01']== 'holiday'){
            $plan.='selected';
        }
        $plan.='>休息日</option>'.PHP_EOL;
        foreach ($tplitem as $k => $tplitems) {
            $plan.='<option value="'.$tplitems['id'].'"';
            if($week_w['week01'] == $tplitems['id']){
                $plan.='selected';
            }
            $plan.='>'.$tplitems['tplname'].'</option>'.PHP_EOL;
        }

        $plan.='</select></div><div class="col-sm-5">'.PHP_EOL;
        if (!empty($weekinfo['week01'])) {
            foreach ($weekinfo['week01'] as $k => $times) {
                $plan.='<span title="'.$times.'/'.$weeknums['week01'][$k].'">【<span>'.$times.'</span><span style="color:#999">/'.$weeknums['week01'][$k].'</span>】</span>'.PHP_EOL;



            }
        }

        $plan.='</div>'.PHP_EOL;
        $plan.='</div>'.PHP_EOL;
        $plan.='</div>'.PHP_EOL;
        $plan.='<div class="form-group">'.PHP_EOL;
        $plan.='<label class="col-xs-12 col-sm-3 col-md-2 control-label"></label>'.PHP_EOL;
        $plan.='<div class="col-sm-12 col-xs-12">'.PHP_EOL;
        $plan.='<label class="col-sm-3 col-xs-12 control-label"><span style="color: red;">*</span>周二时间规划</label>'.PHP_EOL;
        $plan.='<div class="col-sm-4">'.PHP_EOL;
        $plan.='<select name="week02">'.PHP_EOL;
        $plan.='<option disabled selected>请选择</option>'.PHP_EOL;
        $plan.='<option value="holiday"';
        if($week_w['week02']== 'holiday'){
            $plan.='selected';
        }
        $plan.='>休息日</option>'.PHP_EOL;
        foreach ($tplitem as $k => $tplitems) {
            $plan.='<option value="'.$tplitems['id'].'"';
            if($week_w['week02'] == $tplitems['id']){
                $plan.='selected';
            }
            $plan.='>'.$tplitems['tplname'].'</option>'.PHP_EOL;
        }
        
        $plan.='</select></div><div class="col-sm-5">'.PHP_EOL;
        if (!empty($weekinfo['week02'])) {
            foreach ($weekinfo['week02'] as $k => $times) {
                $plan.='<span title="'.$times.'/'.$weeknums['week02'][$k].'">【<span>'.$times.'</span><span style="color:#999">/'.$weeknums['week02'][$k].'</span>】</span>'.PHP_EOL;
            }
        }
        $plan.='</div>'.PHP_EOL;
        $plan.='</div>'.PHP_EOL;
        $plan.='</div>'.PHP_EOL;
        $plan.='<div class="form-group">'.PHP_EOL;
        $plan.='<label class="col-xs-12 col-sm-3 col-md-2 control-label"></label>'.PHP_EOL;
        $plan.='<div class="col-sm-12 col-xs-12">'.PHP_EOL;
        $plan.='<label class="col-sm-3 col-xs-12 control-label"><span style="color: red;">*</span>周三时间规划</label>'.PHP_EOL;
        $plan.='<div class="col-sm-4">'.PHP_EOL;
        $plan.='<select name="week03">'.PHP_EOL;
        $plan.='<option disabled selected>请选择</option>'.PHP_EOL;
        $plan.='<option value="holiday"';
        if($week_w['week03']== 'holiday'){
            $plan.='selected';
        }
        $plan.='>休息日</option>'.PHP_EOL;
        foreach ($tplitem as $k => $tplitems) {
            $plan.='<option value="'.$tplitems['id'].'"';
            if($week_w['week03'] == $tplitems['id']){
                $plan.='selected';
            }
            $plan.='>'.$tplitems['tplname'].'</option>'.PHP_EOL;
        }
        
        $plan.='</select></div><div class="col-sm-5">'.PHP_EOL;
        if (!empty($weekinfo['week03'])) {
            foreach ($weekinfo['week03'] as $k => $times) {
                $plan.='<span title="'.$times.'/'.$weeknums['week03'][$k].'">【<span>'.$times.'</span><span style="color:#999">/'.$weeknums['week03'][$k].'</span>】</span>'.PHP_EOL;
            }
        }
        $plan.='</div>'.PHP_EOL;
        $plan.='</div>'.PHP_EOL;
        $plan.='</div>'.PHP_EOL;
        $plan.='<div class="form-group">'.PHP_EOL;
        $plan.='<label class="col-xs-12 col-sm-3 col-md-2 control-label"></label>'.PHP_EOL;
        $plan.='<div class="col-sm-12 col-xs-12">'.PHP_EOL;
        $plan.='<label class="col-sm-3 col-xs-12 control-label"><span style="color: red;">*</span>周四时间规划</label>'.PHP_EOL;
        $plan.='<div class="col-sm-4">'.PHP_EOL;
        $plan.='<select name="week04">'.PHP_EOL;
        $plan.='<option disabled selected>请选择</option>'.PHP_EOL;
        $plan.='<option value="holiday"';
        if($week_w['week04']== 'holiday'){
            $plan.='selected';
        }
        $plan.='>休息日</option>'.PHP_EOL;
        foreach ($tplitem as $k => $tplitems) {
            $plan.='<option value="'.$tplitems['id'].'"';
            if($week_w['week04'] == $tplitems['id']){
                $plan.='selected';
            }
            $plan.='>'.$tplitems['tplname'].'</option>'.PHP_EOL;
        }
        
        $plan.='</select></div><div class="col-sm-5">'.PHP_EOL;
        if (!empty($weekinfo['week04'])) {
            foreach ($weekinfo['week04'] as $k => $times) {
                $plan.='<span title="'.$times.'/'.$weeknums['week04'][$k].'">【<span>'.$times.'</span><span style="color:#999">/'.$weeknums['week04'][$k].'</span>】</span>'.PHP_EOL;
            }
        }
        $plan.='</div>'.PHP_EOL;
        $plan.='</div>'.PHP_EOL;
        $plan.='</div>'.PHP_EOL;
        $plan.='<div class="form-group">'.PHP_EOL;
        $plan.='<label class="col-xs-12 col-sm-3 col-md-2 control-label"></label>'.PHP_EOL;
        $plan.='<div class="col-sm-12 col-xs-12">'.PHP_EOL;
        $plan.='<label class="col-sm-3 col-xs-12 control-label"><span style="color: red;">*</span>周五时间规划</label>'.PHP_EOL;
        $plan.='<div class="col-sm-4">'.PHP_EOL;
        $plan.='<select name="week05">'.PHP_EOL;
        $plan.='<option disabled selected>请选择</option>'.PHP_EOL;
        $plan.='<option value="holiday"';
        if($week_w['week05']== 'holiday'){
            $plan.='selected';
        }
        $plan.='>休息日</option>'.PHP_EOL;
        foreach ($tplitem as $k => $tplitems) {
            $plan.='<option value="'.$tplitems['id'].'"';
            if($week_w['week05'] == $tplitems['id']){
                $plan.='selected';
            }
            $plan.='>'.$tplitems['tplname'].'</option>'.PHP_EOL;
        }
        
        $plan.='</select></div><div class="col-sm-5">'.PHP_EOL;
        if (!empty($weekinfo['week05'])) {
            foreach ($weekinfo['week05'] as $k => $times) {
                $plan.='<span title="'.$times.'/'.$weeknums['week05'][$k].'">【<span>'.$times.'</span><span style="color:#999">/'.$weeknums['week05'][$k].'</span>】</span>'.PHP_EOL;
            }
        }
        $plan.='</div>'.PHP_EOL;
        $plan.='</div>'.PHP_EOL;
        $plan.='</div>'.PHP_EOL;
        $plan.='<div class="form-group">'.PHP_EOL;
        $plan.='<label class="col-xs-12 col-sm-3 col-md-2 control-label"></label>'.PHP_EOL;
        $plan.='<div class="col-sm-12 col-xs-12">'.PHP_EOL;
        $plan.='<label class="col-sm-3 col-xs-12 control-label"><span style="color: red;">*</span>周六时间规划</label>'.PHP_EOL;
        $plan.='<div class="col-sm-4">'.PHP_EOL;
        $plan.='<select name="week06">'.PHP_EOL;
        $plan.='<option disabled selected>请选择</option>'.PHP_EOL;
        $plan.='<option value="holiday"';
        if($week_w['week06']== 'holiday'){
            $plan.='selected';
        }
        $plan.='>休息日</option>'.PHP_EOL;
        foreach ($tplitem as $k => $tplitems) {
            $plan.='<option value="'.$tplitems['id'].'"';
            if($week_w['week06'] == $tplitems['id']){
                $plan.='selected';
            }
            $plan.='>'.$tplitems['tplname'].'</option>'.PHP_EOL;
        }
        
        $plan.='</select></div><div class="col-sm-5">'.PHP_EOL;
        if (!empty($weekinfo['week06'])) {
            foreach ($weekinfo['week06'] as $k => $times) {
                $plan.='<span title="'.$times.'/'.$weeknums['week06'][$k].'">【<span>'.$times.'</span><span style="color:#999">/'.$weeknums['week06'][$k].'</span>】</span>'.PHP_EOL;
            }
        }
        $plan.='</div>'.PHP_EOL;
        $plan.='</div>'.PHP_EOL;
        $plan.='</div>'.PHP_EOL;
        $plan.='<div class="form-group">'.PHP_EOL;
        $plan.='<label class="col-xs-12 col-sm-3 col-md-2 control-label"></label>'.PHP_EOL;
        $plan.='<div class="col-sm-12 col-xs-12">'.PHP_EOL;
        $plan.='<label class="col-sm-3 col-xs-12 control-label"><span style="color: red;">*</span>周日时间规划</label>'.PHP_EOL;
        $plan.='<div class="col-sm-4">'.PHP_EOL;
        $plan.='<select name="week07">'.PHP_EOL;
        $plan.='<option disabled selected>请选择</option>'.PHP_EOL;
        $plan.='<option value="holiday"';
        if($week_w['week07']== 'holiday'){
            $plan.='selected';
        }
        $plan.='>休息日</option>'.PHP_EOL;
        foreach ($tplitem as $k => $tplitems) {
            $plan.='<option value="'.$tplitems['id'].'"';
            if($week_w['week07'] == $tplitems['id']){
                $plan.='selected';
            }
            $plan.='>'.$tplitems['tplname'].'</option>'.PHP_EOL;
        }
        
        $plan.='</select></div><div class="col-sm-5">'.PHP_EOL;
        if (!empty($weekinfo['week07'])) {
            foreach ($weekinfo['week07'] as $k => $times) {
                $plan.='<span title="'.$times.'/'.$weeknums['week07'][$k].'">【<span>'.$times.'</span><span style="color:#999">/'.$weeknums['week07'][$k].'</span>】</span>'.PHP_EOL;
            }
        }
        $plan.='</div>'.PHP_EOL;
        $plan.='</div>'.PHP_EOL;
        $plan.='</div>'.PHP_EOL;

        $plan.='<div class="form-group">'.PHP_EOL;
        $plan.='<input style="display: block;margin: 0 auto;float: none"  id="btn_submit" onclick="sendForm('.$id.','.$themeid.','.$shopid.')" value="提交" class="btn btn-primary col-lg-1" >'.PHP_EOL;
        $plan.='<input type="hidden" name="token" value="{$_G[\'token\']}" /> '.PHP_EOL;
        $plan.='</div>'.PHP_EOL;
        $plan.='</div>'.PHP_EOL;
        $plan.='</div>'.PHP_EOL;
        $plan.='</div>'.PHP_EOL;
        $plan.='</form> '.PHP_EOL;
        $plan.=''.PHP_EOL;
        $plan.=''.PHP_EOL;

        $ruleBtn_html['data']=$plan;
        return_json(0,'操作成功',$ruleBtn_html);


        // $return_clicent = get_defined_vars();
return $this->view('/shopplan/plan', $return_clicent);
    }
    //每周规划入库
    function plansave(){
        //接受前台post来的数据，入库（增加或者更新处理）
        global $_G,$_P,$_S,$_C;
        $system = $_S;
        $method = 'shopplan_setplan';
        $navtabs= 'shopplan_setplan';

        //获取商家id+分店id
        $themeid = intval($_P['themeid']);
        $storeid=$_P['themeid']?$_P['themeid']:$_P['storeid'];//themeid相当于storeid
        $shopid =$_P['shopid'];
        $id = $_P['id'];


        //获取每周时间规划，如果没有，默认为普通工作日
        $tplweek['week01'] = $_P['week01'];
        $tplweek['week02'] = $_P['week02'];
        $tplweek['week03'] = $_P['week03'];
        $tplweek['week04'] = $_P['week04'];
        $tplweek['week05'] = $_P['week05'];
        $tplweek['week06'] = $_P['week06'];
        $tplweek['week07'] = $_P['week07'];

        if (empty($_P['week01'])) {
            return_json(1,'请选择周一时间规划');
        }elseif (empty($_P['week02'])) {
            return_json(1,'请选择周二时间规划');
        }elseif (empty($_P['week03'])) {
            return_json(1,'请选择周三时间规划');
        }elseif (empty($_P['week04'])) {
            return_json(1,'请选择周四时间规划');
        }elseif (empty($_P['week05'])) {
            return_json(1,'请选择周五时间规划');
        }elseif (empty($_P['week06'])) {
            return_json(1,'请选择周六时间规划');
        }elseif (empty($_P['week07'])) {
            return_json(1,'请选择周日时间规划');
        }

        $data = [
            'storeid'       =>$themeid,                         //商家id的模拟数据
            'shopid'        =>$shopid,                          //店铺id的模拟数据
            'workdays'      =>json_encode($tplweek),            //每周时间规划
            'updated_at'    =>date("Y-m-d H:i:s"),
        ];

        $where = ['id'=>$id];
        $res = ShopplanModel::editTimeConfigByWhere($where,$data);

        if (!$res){
            return_json(1,'操作失败');
        }else{
            return_json(0,'操作成功',$ruleBtn_html);
        }
    }
    //特殊日期管理
    function showspecial(){
        global $_G,$_P,$_S,$_C;
        $system = $_S;
        $method = 'shopplan_setplan';
        $navtabs= 'shopplan_datelist';

        //获取商家id+分店id
        $themeid = intval($_P['themeid']);
        $storeid=$_P['themeid']?$_P['themeid']:$_P['storeid'];//themeid相当于storeid
        $shopid =$_P['shopid']?$_P['shopid']:'1';
        $plantimeid =$_P['plantimeid'];
        $shopname =$_P['shopname'];
        // $id=$_P['id']?$_P['id']:$plantimeid;

        if ($storeid) {
            $item = ShopplanModel::getConfigByStoreId($storeid);
            $shopconfig=json_decode($item['shopconfig'],TRUE);
        }

        //如果有（商家id+店铺id），获取原来配置信息
        if ($storeid && $shopid >= 1) {
            $item = ShopplanModel::getTimeConfigByStoreId($storeid,$shopid);
            $id=$item['id'];//获取分店时间配置表的id
        }


        //获取店铺（storeid或者themeid）的所有规划信息
        $tplitem = ShopplanModel::getSpecialWorktimesListByStoreid($storeid);


        //显示特别日期
        $special_rules=json_decode($item['special_rules'],TRUE);
        //获取时间段+时间段的数量
        if (!empty($special_rules)) {
            foreach ($special_rules as $key => $value) {
                if ($value['tplid'] != 'holiday') {
                    $tplinfo = ShopplanModel::getSpecialWorktimesById($value['tplid']);
                    $special_temp =json_decode($tplinfo['s_work_rules'],TRUE); 
                    foreach ($special_temp as $k => $v) {
                        $specialinfo[$key][$k] = $v["worktimes"];
                        $specialnums[$key][$k] = $v["nums"];

                    }
                }else{
                    $specialinfo[$key][0]='休息日';
                    $specialnums[$key][0] = 0;
                }
            }
        }


        $special='<form id="form3"  enctype ="multipart/form-data" method="post">'.PHP_EOL;
        $special.='<div class="panel panel-default" role="tabpanel" style=""><div>'.PHP_EOL;
        $special.='<div class="panel-heading">特殊日期管理<a href="javascript:isShowSpecial(false)" style="float: right;">关闭</a></div>'.PHP_EOL;
        $special.='<div class="panel-body" >'.PHP_EOL;
        $special.='<div class="form-group" style="margin-bottom:20px">'.PHP_EOL;
        $special.='<div class="col-sm-12 col-xs-12">'.PHP_EOL;
        $special.='<label class="col-sm-3 col-xs-12 control-label"><span style="color: red;">*</span>日期</label>'.PHP_EOL;
        $special.='<label class="col-sm-3 col-xs-12 control-label"><span style="color: red;">*</span>适用规划</label>'.PHP_EOL;
        $special.='<label class="col-sm-3 col-xs-12 control-label"><span style="color: red;">*</span>操作</label>'.PHP_EOL;
        $special.='<div ><span style="color: red;">*</span>规划时间段概况</div>'.PHP_EOL;
        $special.='</div>'.PHP_EOL;
        if (!empty($special_rules)) {
            foreach ($special_rules as $k1 => $special_rule) {
                $special.='<div class="col-sm-12 col-xs-12">'.PHP_EOL;
                $special.='<input type="hidden" name="plan_s_work00_time['.$k1.'][workdays]" value="'.$special_rule['workdays'].'" checked="checked">'.PHP_EOL;
                $special.='<label class="col-sm-2 col-xs-12 control-label">'.$special_rule['workdays'].'</label>'.PHP_EOL;
                $special.='<label class="col-sm-3 col-xs-12 control-label">'.PHP_EOL;
                $special.='<select name="plan_s_work00_time['.$k1.'][tplid]">'.PHP_EOL;
                $special.='<option disabled selected>选择时间规划</option>'.PHP_EOL;
                $special.='<option value="holiday"';
                if ($special_rule['tplid'] == 'holiday'){
                    $special.='selected';
                }
                $special.='>休息日</option>'.PHP_EOL;
                foreach ($tplitem as $k => $tplitems) {
                    $special.='<option value="'.$tplitems['id'].'"';
                    if ($special_rule['tplid'] == $tplitems['id']){
                        $special.='selected';
                    }
                    $special.='>'.$tplitems['tplname'].'</option>'.PHP_EOL;
                }
                
                $special.='</select>'.PHP_EOL;
                $special.='</label>'.PHP_EOL;
                $special.='<label class="col-sm-2 col-xs-12 control-label" style="text-align:center;">'.PHP_EOL;
                $special.='<a style="background-color: #ca4242; padding: 3px 10px;border-radius:5px; text-align:center;color: white;" onclick="delSpecial('.$themeid.','.$shopid.','.$k1.')">删除</a>'.PHP_EOL;
                $special.='</label>'.PHP_EOL;
                $special.='<div class="col-sm-5 col-xs-12 control-label">'.PHP_EOL;
                foreach ($specialinfo[$k1] as $k => $times) {
                    $special.='<span title="'.$times.'/'.$specialnums[$k1][$k].'">【<span>'.$times.'</span><span style="color:#999">/'.$specialnums[$k1][$k].'</span>】</span>'.PHP_EOL;
                }
                
                $special.='</div>'.PHP_EOL;
                $special.='</div>'.PHP_EOL;
            }
        }
        $special.='</div>'.PHP_EOL;
        $special.='<div class="form-group">'.PHP_EOL;
        $special.='<div class="col-sm-12" style="text-align: center;">'.PHP_EOL;
        $special.='<div class="col-sm-2">'.PHP_EOL;

        $special.='</div>'.PHP_EOL;
        $special.='</div>'.PHP_EOL;
        $special.='</div>'.PHP_EOL;
        $special.='</div>'.PHP_EOL;
        $special.='<div class="form-group">'.PHP_EOL;
        $special.='<a style="background-color:#428bca;padding: 5px 10px; color: white;border-radius:5px;float:left;margin-left: 42px;" href="javascript:addSpecial()"><i class="glyphicon glyphicon-plus" title="adddays"></i>新增特殊日期</a>'.PHP_EOL;
        $special.='<input id="btn_submit" value="提交" onclick="sendSpecial('.$id.','.$themeid.','.$shopid.')" class="btn btn-primary col-lg-1" style="display: block;margin: 0 0 0 175px;float: none;padding:4px 6px" >'.PHP_EOL;
        $special.='<input type="hidden" name="token" value="'.$_G['token'].'" />'.PHP_EOL;
        $special.='</div>'.PHP_EOL;
        $special.='</div></div>'.PHP_EOL;
        $special.='</div>'.PHP_EOL;
        $special.='</form> '.PHP_EOL;
        $special.=''.PHP_EOL;
        $special.=''.PHP_EOL;


        $ruleBtn_html['data']=$special;
        return_json(0,'操作成功',$ruleBtn_html);

        // $return_clicent = get_defined_vars();
return $this->view('/shopplan/showspecial', $return_clicent);
    }
    //特殊日期提交（修改+增加+入库）
    function specialsave(){
        global $_G,$_P,$_S,$_C;
        $system = $_S;

        //对接受的数据进行处理
        $themeid = intval($_P['themeid']);
        $storeid=$_P['themeid']?$_P['themeid']:$_P['storeid'];//themeid相当于storeid
        $id=$_P['id'];
        $shopid=isset($_P['shopid'])?$_P['shopid']:'1';

        //获取特殊日期（日期+规划）
        $plan_s_work00_time =$_P['plan_s_work00_time'];
        $plan_s_work01_time =$_P['plan_s_work01_time'];
        //整合添加的日期与修改的日期（原有日期）
        for ($i=0; $i < count($plan_s_work01_time['workdays']); $i++) { 
            if (!empty($plan_s_work01_time['workdays'][$i]) &&  !empty($plan_s_work01_time['tplid'][$i])) {
                $temp_plan['workdays'] = $plan_s_work01_time['workdays'][$i];
                $temp_plan['tplid'] = $plan_s_work01_time['tplid'][$i];
                $plan_s_work00_time[] = $temp_plan;
            }
        }

        if(!empty($plan_s_work00_time)){
            //去除小于当前时间的日期
            foreach($plan_s_work00_time as $timesk=>$timesv){
                if (!empty($timesv['workdays'])) {
                    if (strtotime($timesv['workdays']) <= time()) {
                        unset($plan_s_work00_time[$timesk]);
                    }
                }else{
                    unset($plan_s_work00_time[$timesk]);
                }
            }

            //去除以前存在的日期
            foreach($plan_s_work00_time as $timesk=>$timesv){
                $s_days[]=$timesv['workdays'];//存入特殊日期
                if(isset($plan_s_work00_time[$timesk+1])){
                    if (in_array($plan_s_work00_time[$timesk+1]['workdays'], $s_days)) {
                        return_json(1,'上面已经存在该特殊日期'.$plan_s_work00_time[$timesk+1]['workdays']);
                    }
                }
            }
        }
        sort($plan_s_work00_time); 

        $data = [
            'storeid'       =>$storeid,                         //商家id的模拟数据
            'shopid'        =>$shopid,                          //店铺id的模拟数据
            'special_rules' =>json_encode($plan_s_work00_time), //特殊日期（日期+规划）
            'updated_at'    =>date("Y-m-d H:i:s"),
        ];


        $where = ['id'=>$id];
        $res = ShopplanModel::editTimeConfigByWhere($where,$data);

        if (!$res){
            return_json(1,'操作失败');
        }else{
            return_json(0,'操作成功',$ruleBtn_html);
        }

    }
    //删除分店时间配置
    function delconfig(){
        global $_G,$_P,$_S,$_C;

        $themeid = intval($_P['themeid']);
        $storeid = $_P['storeid']?intval($_P['storeid']):$themeid;
        $shopid  = trim($_P['shopid']);
        $id      = trim($_P['id']);

        if (!$storeid || $shopid < 1){
            show_json(0,['msg'=>'操作数据有误，请刷新页面后重试']);
        }
        //获取店铺配置信息
        $item = ShopplanModel::getConfigById($id);
        if (empty($item) || $item['id'] != $id) {
            show_json(0,['msg'=>'操作数据有误，请刷新页面后重试']);
        }
        $shopinfos=json_decode($item['shopconfig'],TRUE);
        foreach ($shopinfos as $key => $shopvalue) {
            if ($shopinfos[$key]['shopid']==$shopid) {
                unset($shopinfos[$key]);
            }
        }
        $data = [
            'storeid'       =>$storeid,//商家id的模拟数据
            'shopconfig'    =>json_encode($shopinfos),
            'updated_at'    =>date("Y-m-d H:i:s"),
        ];
        //删除分店时间配置
        $res2 = ShopplanModel::delshopconfig($storeid,$shopid);
        //更新店铺分店信息
        $where = ['id'=>$id];
        $res3 = ShopplanModel::editConfigByWhere($where,$data);
        if ($res3){
            show_json(1,['msg'=>'操作成功']);
        }else{
            show_json(0,['msg'=>'操作失败']);
        }
    }
    //列表展示客户预约
    function show() {
        $method = 'shopplan_show';
        global $_G,$_P,$_S,$_C;
        $system  = $_S;
        $themeid = intval($_P['themeid']);
        if($themeid <= 0){
            $themeid = Theme::getDefaultThemenew();
        }
        $theme = Theme::getThemeById($themeid);
        if(empty($theme['id'])){
            return_msg('还没有创建活动,请联系管理员');
        }

        $themelist = Theme::getAllTheme();
        $page_index = max(1,intval($_P['page']));
        $page_size = 50;
        $page_start = ($page_index-1)*$page_size;



        //如果查询的“开始时间”、“结束时间”，都是当前时间，默认从“活动开启日期”到“现在日期”
        if ($_P['plantime']['start']==date('Y-m-d',time()) && $_P['plantime']['end']==date('Y-m-d',time())) {
            unset($_P['plantime']);
        }
        //查询条件：分店id
        $shopid =isset($_P['shopid'])?$_P['shopid']:'all';

        //查询条件：用户信息，可以是用户：姓名、电话、微信昵称、uid
        $search_data = isset($_P['search_data'])?$_P['search_data']:'';
        if ($search_data){
            $search_data = '%'.$search_data.'%';
        }

        if (($shopid==0 && $shopid != NULL) || !empty($shopid) || !empty($search_data) || ($start_day && $end_day)) {


            //查询条件：起止时间
            $plantime=$_P['plantime'];
            if (empty($plantime['start'])){
                $start_day =db_fetchcolumn ( 'SELECT min(plan_at) FROM ' . tablename (plan_user_planning) );
                $start_day =  date('Y-m-d',strtotime($start_day));
            }else{
                $start_day =  $plantime['start'];
            }
            if (empty($plantime['end'])) {
                $end_day=date('Y-m-d',time()+86400*90);

            }else{
                $end_day = $plantime['end'];
            }

            $lists = ShopplanModel::searchPlaned($themeid,$shopid,$search_data,0,0,$start_day,$end_day);
            $total = count($lists);

            $list = ShopplanModel::searchPlaned($themeid,$shopid,$search_data,$page_start,$page_size,$start_day,$end_day);
            $page_total = $total;

            $pager = pagination($page_total,$page_index,$page_size);
        }else{

            $lists = ShopplanModel::getDefaultUserPlaned($themeid,0,0);
            $list = ShopplanModel::getDefaultUserPlaned($themeid,$page_start,$page_size);
            $total = $page_total = count($lists);
            $pager = pagination($page_total,$page_index,$page_size);
        }


        $item = ShopplanModel::getConfigByStoreId($themeid);
        $shopconfig=json_decode($item['shopconfig'],TRUE);
        $agelimit = $item['agelimit'];//门店年龄限制开关，0为关闭，1为开启

        foreach ($list as $key => $value) {
            $list[$key]['p_date']=substr($value['plan_at'],0,11);
            $list[$key]['p_time']= substr($value['plan_at'],-9,6);

            if ($value['birthday']=='0000-00-00 00:00:00') {
                $list[$key]['birthday'] = '';
            } else {
                $list[$key]['birthday']=date('Y-m-d',strtotime($value['birthday']));
            }

            $list[$key]['created_at']=date('Y-m-d',strtotime($value['created_at']));
            foreach ($shopconfig as $k => $v) {
                if ($value['shopid']==$v['shopid']) {
                    $list[$key]['shopname']=$v['name'];
                }
            }
        }
        //Excel导出数据
        if(checksubmit('export_submit', true)){
            $count = $total;
            $page_limit = 2000;
            $pagesize = ceil($count/$page_limit);
            $header = array(
                'uid' => 'UID',
                'nickname' => '昵称',
                'username' => '姓名',
                'mobile' => '手机',
                'shopname' => '门店名称', 
                'p_date' => '预约日期',
                'p_time' => '预约时间',
                'worker_name'=>'员工名称',
                'worker_mobile'=>'员工手机',
                'created_at'=>'下单时间'
            );
            $keys = array_keys($header);
            $html = "\xEF\xBB\xBF";
            foreach ($header as $li) {
                $html .= $li . "\t ,";
            }
            $html .= "\n";

//            for ($j = 1; $j <= $pagesize; $j++) {

                $condition="";
                if ($shopid !='all' ){
                    $condition .= " AND a.shopid='$shopid'";
                }
                if ($search_data){
                    $condition .= " AND ( b.mobile LIKE '%".$search_data."%' OR b.username LIKE '%".$search_data."%' OR a.uid LIKE '%".$search_data."%' OR b.nickname LIKE '%".$search_data."%' )";
                }
                if ($start_day && $end_day){
                    $condition .= "  and a.plan_at between '".$start_day."' and '".$end_day."'";
                }
                $condition .= " ORDER BY a.created_at DESC ";
                $ex_page = $_P['ex_page']?$_P['ex_page']:1;
                $condition.= "LIMIT ". ($ex_page - 1) * $page_limit . ",$page_limit ";

                $sql = " SELECT distinct a.*,b.nickname,b.username,b.mobile,b.avatar,c.mobile as worker_mobile,c.username as worker_name FROM ".tablename(plan_user_planning)." AS a ".
                       " LEFT JOIN ".tablename(t_fans)." AS b ON a.uid=b.uid  
                       LEFT JOIN ".tablename(t_record)." AS d ON a.storeid=d.themeid and a.uid=d.uid
                       LEFT JOIN ".tablename(t_worker)." AS c ON d.workerid=c.uid and d.themeid=c.themeid
                       WHERE a.storeid=$themeid AND b.themeid=$themeid".$condition;

                $list = db_select($sql);

                foreach ($list as $key => $value) {
                    $list[$key]['p_date']=substr($value['plan_at'],0,11);
                    $list[$key]['p_time']=substr($value['plan_at'],0,-6);
                    $list[$key]['created_at']=date('Y-m-d',strtotime($value['created_at']));
                    foreach ($shopconfig as $k => $v) {
                        if ($value['shopid']==$v['shopid']) {
                            $list[$key]['shopname']=$v['name'];
                        }
                    }
                }

                if (!empty($list)) {
                    $size = ceil(count($list) / 500);
                    for ($i = 0; $i < $size; $i++) {
                        $buffer = array_slice($list, $i * 500, 500);
                        foreach ($buffer as $row) {
                            if ($row['nickname']){
                                $row['nickname'] = str_replace(',','',$row['nickname']);
                                $row['nickname'] = str_replace('"','',$row['nickname']);
                            }
                            foreach ($keys as $key) {
                                $data[] = $row[$key];
                            }
                            $user[] = implode("\t ,", $data) . "\t ,";
                            unset($data);
                        }
                        $html .= implode("\n", $user)."\n";
                        unset($user);
                    }
//                }
            }
            $is_end = 0;
            if($ex_page>=$pagesize){
                $is_end = 1;
            }
            //新版本导出合并
            Util::WxJump($_S,$html,'客户预约信息表',$themeid,$is_end,$pagesize);
        }

       
        $return_clicent = get_defined_vars();
return $this->view('/shopplan/show', $return_clicent);
    }
    //删除某个客户预约
    function delplan() {
        global $_G,$_P,$_S,$_C;

        $id = trim($_P['id']);
        if ($id){
            $res = ShopplanModel::delPlan($id);
            if ($res){
                return_tips("操作成功",'','success');
            }else{
                return_tips("操作失败",'','error');
            }
        }
    }
    //修改某个客户预约
    function editplan() {
        global $_G,$_P,$_S,$_C;
        $system = $_S;
        $method = 'shopplan_editplan';
        $themeid = intval($_P['themeid']);
        if($themeid <= 0){
            $themeid = Theme::getDefaultThemenew();
        }
        $theme = Theme::getThemeById($themeid);
        if(empty($theme['id'])){
            return_msg('还没有创建活动,请联系管理员');
        }

        $id = trim($_P['id']);
        if ($id){
            $userplaned = ShopplanModel::getUserPlanById($id);
            $logs = json_decode($userplaned['log']);

            $item = ShopplanModel::getConfigByStoreId($userplaned['storeid']);
            $shopconfig=json_decode($item['shopconfig'],TRUE);
            $agelimit = $item['agelimit'];//门店年龄限制开关，0为关闭，1为开启

            $userplaned['p_date']=date('Y-m-d',strtotime($userplaned['plan_at']));
            $userplaned['p_time']=date('H:i',strtotime($userplaned['plan_at']));
            $userplaned['birthday']=date('Y-m-d',strtotime($userplaned['birthday']));
            $userplaned['created_at']=date('Y-m-d',strtotime($userplaned['created_at']));
            foreach ($shopconfig as $k => $v) {
                if ($userplaned['shopid']==$v['shopid']) {
                    $userplaned['shopname']=$v['name'];
                }
            }
        }
            
        if ($_G['ispost']) {

            //接受并处理前端传值信息
            $shopid = isset($_P['shopid'])?$_P['shopid']:'0';
            $storeid = isset($_P['themeid'])?$_P['themeid']:$_P['storeid'];
            $birthday = $_P['birthday'];
            $note = trim($_P['note']);
            $date = $_P['date'];   //获取前端传送的日期（年+月+日）
            $time = $_P['time'];   //获取前端传送的时间（hh:ii）
            $tplid= $_P['tplid'];
            $uid= $_P['uid'];
            if (empty($uid)) {
                return_tips('用户uid不能为空！', $url, 'error');
            }
            if (empty($date)) {
                return_tips('预约日期不能为空！', $url, 'error');
            }
            if (empty($time)) {
                return_tips('预约时间段不能为空！', $url, 'error');
            }
            if (empty($birthday) && $agelimit == 1) {
                return_tips('宝宝生日不能为空！', $url, 'error');
            }

            //根据宝宝生日，计算宝宝当前月龄
            $age = strtotime($birthday); 
            $now = strtotime("now"); 
            $age=floor(($now-$age)/86400/30);

            //如果有（商家id+店铺id），获取配置信息
            if ($storeid && $shopid >= 1) {
                $item2 = ShopplanModel::getTimeConfigByStoreId($storeid,$shopid);
            }

            //获取规划规则
            $item3 = ShopplanModel::getSpecialWorktimesById($tplid);
            $work_rules=json_decode($item3['s_work_rules'],TRUE);


            //获取已经预约的（时间段+数量）
            $get_item = ShopplanModel::searchUserPlaned4($themeid,$shopid,$date);
            sort($get_item);
            if (!empty($work_rules)) {
                foreach ($work_rules as $k => $v) {
                    foreach ($get_item as $key1 => $value1) {
                        if ($v['worktimes']==substr($value1['p_date'],-5)) {
                            if ($work_rules[$k]['nums']>=$value1['nums']) {
                                $work_rules[$k]['p_nums']=$value1['nums'];
                            }else{
                                return_tips('本时间段预约人数超标！', $url, 'error');
                            }
                        }
                    }
                    if($agelimit==1){
                        //预约年龄区间处理
                        if ($v['ages_start'] > $age) {
                            return_tips('本时间段预约，您的宝宝月龄过小！', $url, 'error');
                        }elseif ($age > $v['ages_end']) {
                            return_tips('本时间段预约，您的宝宝月龄偏大！', $url, 'error');
                        }
                    }
                }
            }

            //前端可以使用$work_rules数据

            $date=date('Y-m-d',strtotime($date));   //获取前端传值的“年”
            $plan_at=$date.' '.$time.':00';


            //整理之后入库
            if (!$id){

                $data = [
                    'uid'           =>$uid,                       //用户id
                    'storeid'       =>$themeid,                           //商家id(活动的themeid)
                    'shopid'        =>$shopid,                            //分店id
                    'plan_at'       =>$plan_at,                           //客户预约（日期+时间）
                    'birthday'      =>date("Y-m-d",strtotime($birthday)), //宝贝生日
                    'created_at'    =>date("Y-m-d H:i:s"),         //预约的创建时间
                    'note'          =>$note,                              //客户留言备注
                    'updated_at'    =>date("Y-m-d H:i:s"),         //更新时间
                    'offline_username'    =>isset($_P['offline_username'])?$_P['offline_username']:'',         //线下姓名
                    'offline_mobile'    =>isset($_P['offline_mobile'])?$_P['offline_mobile']:'',        //线下电话
                ];

                $res = ShopplanModel::insertUserPlan($data);
            }else{
                $where = ['id'=>$id];
                $data = [
                    'uid'           =>$uid,                        //用户id
                    'storeid'       =>$themeid,                            //商家id(活动的themeid)
                    'shopid'        =>$shopid,                             //分店id
                    'plan_at'       =>$plan_at,                            //客户预约（日期+时间）
                    'birthday'      =>date("Y-m-d",strtotime($birthday)),  //宝贝生日
                    'note'          =>$note,                               //客户留言备注
                    'updated_at'    =>date("Y-m-d H:i:s"),          //更新时间
                ];

                $res = ShopplanModel::editUserPlanByWhere($where,$data);
            }

            if (!$res){
                return_tips('操作失败', $url, 'error');
            }else{
                return_tips('操作成功！',webUrl('shopplan.show',array('themeid'=>$themeid)), 'success');
            }
        }
        $return_clicent = get_defined_vars();
return $this->view('/shopplan/editplan', $return_clicent);
    }
    //客户预约表（返回前端数据填写的form）
    function userplan() {
        global $_P,$_G,$_S,$_C;

        if (!$_G['ispost']) {
            return_json(1,'发生了意外');
        } else {
            $themeid = isset($_P['themeid'])?$_P['themeid']:'';
            $theme = Theme::getThemeById($themeid);
            if (!$themeid || !$theme) {
                return_json(1,'活动入口不正确');
            } else {
                //接受并处理前端传值信息
                $shopid = isset($_P['shopid'])?$_P['shopid']:'1';
                $storeid = isset($_P['themeid'])?$_P['themeid']:$_P['storeid'];
                $date=$_P['date'];//获取前端页面点击“日期”后的传值
                $totalnums=$_P['totalnums'];//传值日期的可预约客户总数
                $planed=$_P['planed'];//传值日期的已经预约数
                $tplid=$_P['tplid'];//传值日期的时间规划值
                $id=$_P['id'];//传值日期的时间规划值

                //开始获取店铺-分店配置信息
                if ($storeid) {
                    $item = ShopplanModel::getConfigByStoreId($storeid);
                    $agelimit = $item['agelimit'];//门店年龄限制开关，0为关闭，1为开启
                }


                if ($id) {
                    $userplaned = ShopplanModel::getUserPlanById($id);
                    $userplaned['birthday']=date('Y-m-d',strtotime($userplaned['birthday']));
                }

                //根据宝宝生日，计算宝宝当前月龄
                $birthday=$userplaned['birthday'];
                if (empty($birthday)) {
                    unset($age);
                }else{
                    $age = strtotime($birthday); 
                    $now = time(); 
                    $age=floor(($now-$age)/86400/30);
                }


                //如果有（商家id+店铺id），获取配置信息
                if ($storeid && $shopid >= 1) {
                    $item2 = ShopplanModel::getTimeConfigByStoreId($storeid,$shopid);
                }

                //规划规则
                $item3 = ShopplanModel::getSpecialWorktimesById($tplid);
                $work_rules=json_decode($item3['s_work_rules'],TRUE);


                //获取已经预约的（时间段+数量）
                $get_item = ShopplanModel::searchUserPlaned4($themeid,$shopid,$date);
                sort($get_item);


                foreach ($work_rules as $k => $v) {
                    foreach ($get_item as $key1 => $value1) {
                        if ($v['worktimes']==substr($value1['p_date'],-5)) {
                            if ($work_rules[$k]['nums']>=$value1['nums']) {
                                $work_rules[$k]['p_nums']=$value1['nums'];
                            }else{
                                return_json(1,'本时间段预约人数超标！');//报错，提示本时间段预约满员
                            }
                        }
                    }
                }
                $worktimes_list_arr = [];
                foreach ($work_rules as $key => $value) {
                    $value['p_nums']=!empty($value['p_nums'])?$value['p_nums']:'0';

                    //后台添加预约时，生日月龄限制失效
                    if ($value['p_nums'] < $value['nums'] && $item3['agelimit']==1 && empty($age)) {
                        array_push($worktimes_list_arr,$value['worktimes']);
                    }elseif ($value['p_nums'] < $value['nums'] && $item3['agelimit']==1 && $value['ages_start'] <= $age && $age <= $value['ages_end']) {
                        array_push($worktimes_list_arr,$value['worktimes']);
                    }elseif ($value['p_nums'] < $value['nums'] && $item3['agelimit']==0){
                        array_push($worktimes_list_arr,$value['worktimes']);
                    }
                    //如果是今天，时间段小于等于2小时之内的，去除
                    $arr=[];
                    if ($date==date("Y-m-d")){
                        $time=$date.' '.$value['worktimes'].':00';
                        if (strtotime($time) - time() <= 0){
                            array_push($arr,$value['worktimes']);
                            $worktimes_list_arr = array_merge(array_diff($worktimes_list_arr, $arr));

                        }
                    }

                }


                //前端可以使用$work_rules数据


                //拼接一个前端数据填写表
                $ruleBtn_html="<table width='90%' border='0px' style='text-align:left; margin-left:20px;'>".PHP_EOL;
                
                $ruleBtn_html.="<tr>".PHP_EOL;
                $ruleBtn_html.="<th style='height: 40px;'>预约日期：<input type=\"text\" name=\"date\" value=\"{$date}\" readonly=\"readonly\"/></th>".PHP_EOL;
                $ruleBtn_html.="<tr>".PHP_EOL;

                $ruleBtn_html.="<tr>".PHP_EOL;
                $ruleBtn_html.="<th style='height: 40px;'>预约时间：".PHP_EOL;
                $ruleBtn_html.="<select name=\"time\">".PHP_EOL;
                $ruleBtn_html.="<option disabled selected>请选择时间</option>".PHP_EOL;
                foreach ($worktimes_list_arr as $key => $value) {
                    $ruleBtn_html.="<option value=\"{$value}\">{$value}</option>".PHP_EOL;
                }
                $ruleBtn_html.="</select>".PHP_EOL;
                $ruleBtn_html.="<tr>".PHP_EOL;
                if ($agelimit==1) {
                    $ruleBtn_html.="<tr>".PHP_EOL;
                    $ruleBtn_html.="<th style='height: 40px;'>宝贝生日：";
                    $ruleBtn_html.="<input type=\"date\" name=\"birthday\" min=\"1921-01-01\" max=\"2030-12-31\" value=\"{$userplaned['birthday']}\">";
                    $ruleBtn_html.="</th>".PHP_EOL;
                    $ruleBtn_html.="<tr>".PHP_EOL;
                }

                $ruleBtn_html.="<tr>".PHP_EOL;
                $ruleBtn_html.="<th style='height: 40px;'>留言备注：<input type=\"text\" name=\"note\" value=\"{$userplaned['note']}\" maxlength=\"30\" size=\"30\" value=\"{$userplaned['note']}\" /></th>".PHP_EOL;
                $ruleBtn_html.="<tr>".PHP_EOL;

                $ruleBtn_html.="<tr>".PHP_EOL;
                $ruleBtn_html.="<th><input type=\"hidden\" name=\"shopid\" value=\"{$shopid}\"/><input type=\"hidden\" name=\"tplid\" value=\"{$tplid}\"/></th>".PHP_EOL;
                $ruleBtn_html.="<tr>".PHP_EOL;

                $ruleBtn_html.="</table>".PHP_EOL;

                $format_res = [
                    'ruleBtn_html'=>$ruleBtn_html,
                ];
                return_json(0,'操作成功',$format_res);

            }
        }
    }
    //添加1个客户预约
    function adplan(){
        global $_G,$_P,$_S,$_C;
        $system = $_S;
        $method = 'shopplan_editplan';
        $op = isset($_P['op'])?$_P['op']:'display';
        $themeid = intval($_P['themeid']);
        if($themeid <= 0){
            $themeid = Theme::getDefaultThemenew();
        }
        $theme = Theme::getThemeById($themeid);
        if(empty($theme['id'])){
            return_msg('还没有创建活动,请联系管理员');
        }
        $id = trim($_P['id']);
        $storeid = $_P['storeid']?intval($_P['storeid']):$themeid;

        $item = ShopplanModel::getConfigByStoreId($themeid);
        $shopconfig=json_decode($item['shopconfig'],TRUE);

        $return_clicent = get_defined_vars();
return $this->view('/shopplan/adplan', $return_clicent);
    }
    //增加特殊工作日（日期+规划）
    function addspecials(){
        global $_G,$_P,$_S,$_C;
        $system = $_S;
        $method = 'shopplan_setplan';
        $navtabs= 'shopplan_addspecials';        

        $shopname  =$_P['shopname'];
        $id        =$_P['id'];
        $plantimeid        =$id;
        $shopid    =$_P['shopid'];
        $themeid=$_P['themeid'];
        $storeid=isset($_P['storeid'])?$_P['storeid']:$themeid;

        //获取店铺（storeid或者themeid）的所有规划信息
        $tplitem = ShopplanModel::getSpecialWorktimesListByStoreid($storeid);

        if ($storeid) {
            $item = ShopplanModel::getConfigByStoreId($storeid);
        }

        //如果没有分店名称，查找分店名称
        $shopconfig=json_decode($item['shopconfig'],TRUE);
        if (empty($shopname) && !empty($item['shopconfig'])) {
            foreach ($shopconfig as $key => $value) {
                if ($shopconfig[$key]['shopid'] == $shopid ) {
                    $shopname =$value['name'];

                }
            }
        }

        //接受前台post来的数据，入库（增加或者更新处理）
        if ($_G['ispost']) {
            $shopname  =$_P['shopname'];
            $id        =$_P['id'];
            $shopid    =$_P['shopid'];
            $storeid    =$_P['storeid'];
            $plantimeid        =$id;
            //如果有分店时间配置表id，或者有（商家id+店铺id），获取原来配置信息
            if ($storeid && $shopid >= 1) {
                $item = ShopplanModel::getTimeConfigByStoreId($storeid,$shopid);
            }

            $id=$item['id'];//获取分店时间配置表的id


            $workdays=$_P['plan_s_work00_time'];
            //日期必须大于当前时间
            if (strtotime($workdays) <= time()) {
                return_tips('日期必须大于当前时间！', $url, 'error');
            }

            $tplid =$_P['week01'];//规划id
            if(empty($_P['plan_s_work00_time']) || empty($workdays)){
                return_tips('日期不能为空！', $url, 'error');
            }elseif (empty($tplid)) {
                return_tips('请选择时间规划！', $url, 'error');
            }


            //获取当前特殊工作日，日期，以及规划规则
            $special_rules_now['workdays'] =$workdays;
            $special_rules_now['tplid']    =$tplid;


            //获取原来数据库中的“特殊工作日”
            $item2 = ShopplanModel::getTimeConfigById($id);
            $special_rules=json_decode($item['special_rules'],TRUE);

            //如果原来特殊工作日规则为空，则增加当前规则
            if (empty($special_rules)) {
                $special_rules[0]=$special_rules_now;
            }else{
                foreach ($special_rules as $key => $value) {
                    if ($workdays==$value['workdays']) {
                        return_tips('已经存在这个特殊日期！', $url, 'error');
                    }
                }
                array_push($special_rules,$special_rules_now);
                sort($special_rules);               
            }

            $data = [
                'special_rules' =>json_encode($special_rules),     //特殊普通工作日规则
                'updated_at'    =>date("Y-m-d H:i:s"),
            ];


            $where = ['id'=>$id];
            $res = ShopplanModel::editTimeConfigByWhere($where,$data);
            if (!$res){
                return_tips('操作失败', $url, 'error');
            }else{
                return_tips('操作成功', createWebUrlPlugin('shopplan.showspecial',array('shopid'=>$shopid,'themeid'=>$themeid)), 'success');
            }

        }

        $return_clicent = get_defined_vars();
return $this->view('/shopplan/setspecials', $return_clicent);
    }
    //删除特殊工作日（日期+规划）
    function delspecials(){
        global $_G,$_P,$_S,$_C;
        $system             = $_S;
        $shopid             =$_P['shopid'];
        $special_rules_id   =$_P['special_rules_id'];
        $themeid=$_P['themeid'];
        $storeid=isset($_P['storeid'])?$_P['storeid']:$themeid;
        //如果有（商家id+店铺id），获取原来配置信息
        if ($storeid && $shopid >= 1) {
            $item = ShopplanModel::getTimeConfigByStoreId($storeid,$shopid);
            $id=$item['id'];//获取分店时间配置表的id
        }

        //获取原来数据库中的“特殊工作日”
        $item = ShopplanModel::getTimeConfigById($id);
        $special_rules=json_decode($item['special_rules'],TRUE);

        //删除选定的“special_rules_id”的工作日（日期+规划）
        unset($special_rules[$special_rules_id]);

        $data = [
            'special_rules' =>json_encode($special_rules),     //特殊普通工作日规则
            'updated_at'    =>date("Y-m-d H:i:s"),
        ];

        $where = ['id'=>$id];
        $res = ShopplanModel::editTimeConfigByWhere($where,$data);
        if (!$res){
            return_json(1,'操作失败');
        }else{
            return_json(0,'操作成功',$ruleBtn_html);
        }
    }
    //规划添加
    function setspecial() {
        global $_G,$_P,$_S,$_C;
        $system    = $_S;
        $method = 'shopplan_setplan';
        $navtabs= 'shopplan_setspecial';

        $plantimeid=$_P['plantimeid'];
        $themeid=$_P['themeid'];
        $storeid=isset($_P['storeid'])?$_P['storeid']:$themeid;

        //（某商家）的店铺配置信息
        if ($storeid){
            $item = ShopplanModel::getConfigByStoreId($storeid);
        }


        //获取店铺（storeid或者themeid）的所有规划信息
        $tplitem = ShopplanModel::getSpecialWorktimesListByStoreid($storeid);

        if ($_G['ispost']) {

            if (empty($_P['tplname'])) {
                return_tips('规划名称不能为空！','', 'error');
            } elseif (empty($_P['s_work'])) {
                return_tips('时间规则不能为空！','', 'error');
            } else{

                $tplname=trim($_P['tplname']);//获取规划名称

                //规划名称不能重复
                if ($tplitem && $tplname) {
                    foreach ($tplitem as $key => $value) {
                        if ($tplname==$value['tplname']) {
                            return_tips('规划名称与其它规划重复！','', 'error');
                        }
                    }
                }

                $totalnums=0;//计算通用时间规则下，每天可以预约客户总数
                sort($_P['s_work']);//获取“通用时间规则”
                $work_rules01=$_P['s_work'];//获取“通用时间规则”

                // 判断是否保留二级数组键 (所有二级数组键必须相同)
                $ndArr = array_keys(end($work_rules01));

                //降维,也可以用implode,将一维数组转换为用逗号连接的字符串
                foreach ($work_rules01 as $k=>$v){
                    $v = join(",",$v);  //拼接的字符串
                    $v1=substr($v,0,5); //取前5位，即08:45这种
                    $temp[]  = $v;
                    $temp2[] = $v1;
                }

                //去掉重复的字符串,也就是重复的一维数组
                $temp2 = array_unique($temp2); 

                //把取前5位的字符串，补充上后面的值
                foreach ($temp2 as $k2 => $v2)
                {
                    foreach ($temp as $key => $value) {
                        if(strpos($value,$v2)==0 && $k2==$key){
                            $temp2[$k2] = $value;
                        }
                    }
                }

                //再将拆开的数组重新组装
                foreach ($temp2 as $k2 => $v2)
                {
                    $tempArr = explode(",",$v2); 
                    foreach($tempArr as $ndkey => $ndval){
                        $work_rules[$k2][$ndArr[$ndkey]] = $ndval;
                    }

                }
                sort($work_rules);
                //以上处理，当天选择的时间段，不能相同


                //遍历通用时间规则，获取当天可预约客户总数
                foreach ($work_rules as $key => $value) {
                    $totalnums = $totalnums + $value['nums'];
                }
                // $agelimit=$_P['agelimit'];//获取规划名称

                //整理入库数据
                $data = [
                    'plantimeid'    =>$plantimeid,                  //分店时间配置表id
                    'storeid'       =>$storeid,                     //店铺id
                    'tplname'       =>$tplname,                     //规划名称
                    's_work_rules'  =>json_encode($work_rules),     //本规划规则
                    'totalnums'     =>$totalnums,                   //当天可预约客户总数（本规划）
                    'status'        =>1,                            //规划状态，1，默认开启，0为关闭
                    // 'agelimit'      =>$agelimit,                    //年龄限制，0，默认关闭，1为开启
                    'updated_at'    =>date("Y-m-d H:i:s"),
                ];

                //入库
                $res = ShopplanModel::insertSpecialWorktimes($data);
                if (!$res){
                    return_tips('操作失败','', 'error');
                    // show_json(0,['msg'=>'操作失败']);
                }else{
                    return_tips('操作成功',webUrl('shopplan.speciallist',array('themeid'=>$themeid)), 'success');
                    // show_json(1,['msg'=>'操作成功']);
                }

            }

        }

        $return_clicent = get_defined_vars();
return $this->view('/shopplan/specialplan', $return_clicent);
    }
    //规划编辑
    function editspecial() {
        global $_G,$_P,$_S,$_C;
        $system = $_S;
        $method = 'shopplan_setplan';
        $navtabs= 'shopplan_editspecial';

        $plantimeid=$_P['plantimeid'];
        $id=$_P['id'];
        $themeid=$_P['themeid'];
        $storeid=isset($_P['storeid'])?$_P['storeid']:$themeid;

        //获取本id的自定义规划信息
        if ($id) {
            $item = ShopplanModel::getSpecialWorktimesById($id);
            $s_work_rules=json_decode($item['s_work_rules'],TRUE);
        }

        //（某商家）的店铺配置信息
        if ($storeid){
            $store_item = ShopplanModel::getConfigByStoreId($storeid);
            //获取店铺（storeid或者themeid）的所有规划信息
            $tplitem = ShopplanModel::getSpecialWorktimesListByStoreid($storeid);            
        }
        $last_time = '8:45';
        if ($s_work_rules){
            $last_key = count($s_work_rules)-1;
            $datetime = array();
            foreach ($s_work_rules as $k => $v){
                $datetime[] = $v['worktimes'];
            }
            array_multisort($datetime,SORT_ASC,$s_work_rules);
            $last_time = $s_work_rules[$last_key]['worktimes'];
        }

        $plan='<form id="form3"  enctype ="multipart/form-data" method="post">'.PHP_EOL;
        $plan.='<div class="panel panel-default" role="tabpanel" style="">'.PHP_EOL;
        $plan.='<div class="panel-heading">编辑规划<a href="javascript:isShowPlan(false)" style="float: right;">关闭</a></div>'.PHP_EOL;
        $plan.='<div class="panel-body" >'.PHP_EOL;
        $plan.='<div class="form-group">'.PHP_EOL;
        $plan.='<label class="col-xs-12 col-sm-2 col-md-2 control-label"><b>规划名称</b></label>'.PHP_EOL;
        $plan.='<div class="col-sm-10 col-xs-12" >'.PHP_EOL;
        $plan.='规划名称<label class="radio-inline"><input class="form-control span3" type="text" name="tplname" maxlength="18" value="'.$item['tplname'].'" style="max-width: 400px;width: 400px;"></label>'.PHP_EOL;
        $plan.='<span class="help-block">最大长度18个字</span>'.PHP_EOL;
        $plan.='</div>'.PHP_EOL;
        $plan.='</div>'.PHP_EOL;
        $plan.='<div class="form-group">'.PHP_EOL;
        $plan.='<label class="col-xs-12 col-sm-2 col-md-2 control-label"><b>规划规则</b></label>'.PHP_EOL;
        $plan.='<div class="col-sm-10 col-xs-12">'.PHP_EOL;
        $plan.='<table class="table">'.PHP_EOL;
        $plan.='<thead>'.PHP_EOL;
        $plan.='<tr>'.PHP_EOL;
        $plan.='<th width="10%">每工作日可预约时间段</th>'.PHP_EOL;
        $plan.='<th width="20%">本时间段可预约客户数量</th>'.PHP_EOL;
        if ($store_item['agelimit']==1){
            $plan.='<th width="60%" colspan="2">本时间段适用的宝宝月龄</th>'.PHP_EOL;
        }

        $plan.='<th width="10%">操作</th>'.PHP_EOL;
        $plan.='</tr>'.PHP_EOL;
        $plan.='</thead>'.PHP_EOL;
        $plan.='<tbody id="yx_special_time_items">'.PHP_EOL;
        if(empty($s_work_rules)){
            $plan.='<tr >'.PHP_EOL;
            $plan.='<td><input class="time_picker" type="text" id="time_picker_baby" name="s_work[0][worktimes]" value="08:45"/></td>'.PHP_EOL;
            $plan.='<td><input name="s_work[0][nums]" type="number" min="0" value="1"/></td>'.PHP_EOL;
            if($store_item['agelimit']==1){
                $plan.='<td>开始月龄<input type="number" name="s_work[0][ages_start]" value="0" min="0"></td><td>最大月龄<input type="number" name="s_work[0][ages_end]" value="1200" min="0"></td>'.PHP_EOL;
            }

            $plan.='<td><input  name="s_work[0][id]" type="hidden" value="" /><a style="background-color: #ca4242; padding: 3px 10px;border-radius:5px; text-align:center;color: white;" href="javascript:;" onclick="removePlanItem(this)">删除</a></td>'.PHP_EOL;
            $plan.='</tr>'.PHP_EOL;
        }else{
            foreach ($s_work_rules as $key => $w_rule) {
                $plan.='<tr>'.PHP_EOL;
                $plan.='<td><input class="time_picker" id="time_picker'.$key.'" name="s_work['.$key.'][worktimes]" type="text" value="'.$w_rule['worktimes'].'"/></td>'.PHP_EOL;
                $plan.='<td><input name="s_work['.$key.'][nums]" type="number" min="0"  value="'.$w_rule['nums'].'"/></td>'.PHP_EOL;
                if($store_item['agelimit']==1){
                    $plan.='<td>开始月龄<input type="number" name="s_work['.$key.'][ages_start]" value="'.$w_rule['ages_start'].'" min="0">&nbsp;&nbsp;&nbsp;&nbsp;最大月龄<input type="number" name="s_work['.$key.'][ages_end]" value="'.$w_rule['ages_end'].'" min="0"></td>'.PHP_EOL;
                }
                $plan.='<td><input  name="s_work['.$key.'][id]" type="hidden" value="" /><a style="background-color: #ca4242; padding: 3px 10px;border-radius:5px; text-align:center;color: white;" href="javascript:;" onclick="removePlanItem(this)">删除</a></td>'.PHP_EOL;
                $plan.='</tr>'.PHP_EOL;
            }
        }
        $plan.='</tbody>'.PHP_EOL;
        $plan.='</table>'.PHP_EOL;
        $plan.='<a href="javascript:;" onclick="addspecialPlan();" style="background-color:#428bca;padding: 5px 10px; color: white;border-radius:5px;"><i class="glyphicon glyphicon-plus" title="addPlan"></i>添加时间段</a>'.PHP_EOL;
        $plan.='</div>'.PHP_EOL;
        $plan.='</div>'.PHP_EOL;
        $plan.='<div class="form-group">'.PHP_EOL;
        $plan.='<div class="col-sm-12">'.PHP_EOL;
        $plan.='<input  id="btn_submit"  value="提交" class="btn btn-primary col-lg-1" onclick="sendEditRules('.$id.')">'.PHP_EOL;
        $plan.='<input type="hidden" name="token" value="'.$_G['token'].'" />'.PHP_EOL;
        $plan.='</div>'.PHP_EOL;
        $plan.='</div>'.PHP_EOL;
        $plan.='</div>'.PHP_EOL;
        $plan.='</div>'.PHP_EOL;
        $plan.='</form>'.PHP_EOL;
        $plan.=''.PHP_EOL;
        $plan.=''.PHP_EOL;

        $ruleBtn_html['data']=$plan;
        $ruleBtn_html['last_time']=$last_time;
        return_json(0,'操作成功',$ruleBtn_html);

        // $return_clicent = get_defined_vars();
return $this->view('/shopplan/editspecial', $return_clicent);
    }
    //规划编辑提交
    function editspecialsave(){
        global $_G,$_P,$_S,$_C;
        $system = $_S;

        $plantimeid=$_P['plantimeid'];
        $id=$_P['id'];
        $themeid=$_P['themeid'];
        $storeid=isset($_P['storeid'])?$_P['storeid']:$themeid;
        //（某商家）的店铺配置信息
        if ($storeid){
            //获取店铺（storeid或者themeid）的所有规划信息
            $tplitem = ShopplanModel::getSpecialWorktimesListByStoreid($storeid);            
        }
        //对接受的数据进行处理
        
        if (empty($_P['tplname'])) {
            return_tips("规划名称不能为空！",'','error');
        } elseif (empty($_P['s_work'])) {
            return_tips("时间规则不能为空！",'','error');
        } else{

            $tplname=trim($_P['tplname']);//获取规划名称

            //规划名称不能重复
            if ($tplitem && $tplname) {
                foreach ($tplitem as $key => $value) {
                    if ($tplname==$value['tplname'] && $value['id'] != $id) {
                        return_json(1,'规划名称与其它规划重复！');
                    }
                }
            }

            $totalnums=0;//计算通用时间规则下，每天可以预约客户总数
            $s_work = $_P['s_work'];//获取“通用时间规则”
            sort($s_work);
            $work_rules01=$s_work;//获取“通用时间规则”

            // 判断是否保留二级数组键 (所有二级数组键必须相同)
            $ndArr = array_keys(end($work_rules01));

            //降维,也可以用implode,将一维数组转换为用逗号连接的字符串
            foreach ($work_rules01 as $k=>$v){
                $v = join(",",$v);  //拼接的字符串
                $v1=substr($v,0,5); //取前5位，即08:45这种
                $temp[]  = $v;
                $temp2[] = $v1;
            }

            //去掉重复的字符串,也就是重复的一维数组
            $temp2 = array_unique($temp2); 

            //把取前5位的字符串，补充上后面的值
            foreach ($temp2 as $k2 => $v2)
            {
                foreach ($temp as $key => $value) {
                    if(strpos($value,$v2)==0 && $k2==$key){
                        $temp2[$k2] = $value;
                    }
                }
            }

            //再将拆开的数组重新组装
            foreach ($temp2 as $k2 => $v2)
            {
                $tempArr = explode(",",$v2); 
                foreach($tempArr as $ndkey => $ndval){
                    $work_rules[$k2][$ndArr[$ndkey]] = $ndval;
                }

            }
            sort($work_rules);
            //以上处理，当天选择的时间段，不能相同


            //遍历通用时间规则，获取当天可预约客户总数
            foreach ($work_rules as $key => $value) {
                $totalnums = $totalnums + $value['nums'];
            }

            //整理入库数据
            $data = [
                'plantimeid'    =>$plantimeid,                  //分店时间配置表id
                'storeid'       =>$storeid,                     //店铺id
                'tplname'       =>$tplname,                     //规划名称
                's_work_rules'  =>json_encode($work_rules),     //本规划规则
                'totalnums'     =>$totalnums,                   //当天可预约客户总数（本规划）
                'status'        =>1,
                'updated_at'    =>date("Y-m-d H:i:s"),
            ];

            //入库
            $where = ['id'=>$id];
            $res = ShopplanModel::editSpecialWorktimesByWhere($where,$data);

            if (!$res){
                return_json(1,'操作失败');
            }else{
                return_json(0,'操作成功',$ruleBtn_html);
            }

        }

    }
    //改变规划status状态
    function tplstatus(){
        global $_G,$_P,$_S,$_C;
        $system = $_S;

        $plantimeid=$_P['plantimeid'];
        $shopname=$_P['shopname'];
        $s_workid=$_P['s_workid'];
        $shopid=$_P['shopid'];
        $themeid=$_P['themeid'];
        $storeid=isset($_P['storeid'])?$_P['storeid']:$themeid;
        $status    =$_P['status'];

        if ($status==1) {
            $status = 0;
        }elseif ($status==0) {
            $status = 1;
        }


        //整理入库数据
        $data = [
            'status'        =>$status,
            'updated_at'    =>date("Y-m-d H:i:s"),
        ];

        //入库
        $where = ['id'=>$s_workid];
        $res = ShopplanModel::editSpecialWorktimesByWhere($where,$data);

        if (!$res){
            return_tips("操作失败",'','error');
        }else{
            return_tips("操作成功",webUrl('shopplan.speciallist',array('themeid'=>$themeid,'storeid'=>$storeid,'plantimeid'=>$plantimeid,'shopname'=>$shopname,'shopid'=>$shopid)),'success');
        }

    }
    /*
    //改变规划年龄限制的状态
    function agelimit(){
        global $_G,$_P,$_S,$_C;
        $system = $_S;

        $plantimeid=$_P['plantimeid'];
        $shopname   =$_P['shopname'];
        $s_workid   =$_P['s_workid'];
        $shopid     =$_P['shopid'];
        $themeid=$_P['themeid'];
        $storeid=isset($_P['storeid'])?$_P['storeid']:$themeid;
        $agelimit   =$_P['agelimit'];

        if ($agelimit==1) {
            $agelimit = 0;
        }elseif ($agelimit==0) {
            $agelimit = 1;
        }


        //整理入库数据
        $data = [
            'agelimit'      =>$agelimit,
            'updated_at'    =>date("Y-m-d H:i:s"),
        ];

        //入库
        $where = ['id'=>$s_workid];
        $res = ShopplanModel::editSpecialWorktimesByWhere($where,$data);

        if (!$res){
            return_tips("操作失败",'','error');
        }else{
            return_tips("操作成功",'','success');
        }
    }*/
    //规划列表
    function speciallist() {
        global $_G,$_P,$_S,$_C;
        $system = $_S;
        $method = 'shopplan_setplan';
        $navtabs= 'shopplan_speciallist';

        $id=$_P['id'];
        $shopname=$_P['shopname'];
        $plantimeid=$_P['plantimeid'];
        $shopid=$_P['shopid'];
        $themeid=$_P['themeid'];
        $storeid=isset($_P['storeid'])?$_P['storeid']:$themeid;
        if($themeid <= 0){
            $themeid = Theme::getDefaultThemenew();
        }
        $themelist = Theme::getAllTheme();


        if ($storeid && $shopid >= 1) {
            $item = ShopplanModel::getTimeConfigByStoreId($storeid,$shopid);
            $plantimeid=$id=$item['id'];//获取分店时间配置表的id
        }
        
        if ($storeid){
            $item = ShopplanModel::getConfigByStoreId($storeid);
            //获取店铺（storeid或者themeid）的所有规划信息
            $tplitem = ShopplanModel::getAllSpecialWorktimesList($storeid);
        }
        

        $return_clicent = get_defined_vars();
return $this->view('/shopplan/speciallist', $return_clicent);
    }
    //删除规划
    function delspecial() {
        global $_G,$_P,$_S,$_C;

        $id = trim($_P['id']);
        if ($id){
            $res = ShopplanModel::delSpecial($id);
            if ($res){
                return_tips("操作成功",'','success');
            }else{
                return_tips("操作失败",'','error');
            }
        }
    }
    //日历界面
    function calendar(){
        global $_P,$_G,$_S,$_C;

        //获取当前年
        $year=$_P['y_now']?$_P['y_now']:date('Y');
        //获取当年月
        $month_n=$_P['m_n']?$_P['m_n']:date('m');

        $date = $year.'-'.$month_n.'-1';   //获取前端传送的时间（时间戳，或者年月）
        $p_year=$year;   //获取前端传值的“年”
        $p_month=$month_n;  //获取前端传值的“月”
        $year_now=date('Y');//获取当前年
        $month=date('m');//获取当年月
        

        //如果前端传值小于等于当前时间(年+月)，从当前月份开始遍历预约时间
        if (strtotime($date) <= time() || ($p_year == $year_now && $p_month == $month)) {
            $j = date("t"); //获取当前月份天数
            // $start_time = time();  //获取今天的时间戳
            $start_time = strtotime(date($year_now.'-'.$month.'-01'));  //获取本月第一天时间戳
            // $day=date('d');//获取今天是当前月的第几天
            // $j=$j-$day;//本月还剩余几天（不包括本天）
            // if ($j==0) {//如果是本月的最后一天
            //     $p_month=$p_month+1;
            // }
            $data = array();
            for($i=0;$i<$j;$i++){
                $data[] = date('Y-m-d',$start_time+($i)*86400); //本月剩余天，每隔一天赋值给数组
            }
        }
        if ($p_year > $year_now || ($p_year == $year_now && $p_month > $month)){
            $j = date("t",strtotime($date)); //获取当前月份天数
            $start_time = strtotime(date($p_year.'-'.$p_month.'-01'));  //获取本月第一天时间戳
            $data = array();
            for($i=0;$i<$j;$i++){
                 $data[] = date('Y-m-d',$start_time+($i)*86400); //每隔一天赋值给数组
            }
        }
        //$data是需要给前端传值的“日期信息”，需要继续处理，给每一个“日期”加上"已预约数量/总预约数量"

        $themeid = $_P['themeid'];//获取themeid，或者说店铺id
        $storeid = $_P['storeid']?$_P['storeid']:$themeid;
        $shopid = isset($_P['shopid'])?$_P['shopid']:'1';  //获取分店shopid
        $birthday = $_P['birthday'];
        $theme = Theme::getThemeById($themeid);

        //根据宝宝生日，计算宝宝当前月龄
        if (empty($birthday)) {
            unset($age);
        }else{
            $age = strtotime($birthday); 
            $now = time(); 
            $age=floor(($now-$age)/86400/30);
        }


        //开始获取店铺-分店-配置信息
        if ($storeid) {
            $item = ShopplanModel::getConfigByStoreId($storeid);
            $agelimit = $item['agelimit'];//门店年龄限制开关，0为关闭，1为开启
            $end_date = $item['end_date'];//活动的最后1天 
            $start_date = $item['start_date'];//活动的开始预约时间
        }


        //查找分店信息
        if (!empty($item['shopconfig'])) {
            $shopconfig=json_decode($item['shopconfig'],TRUE);
            foreach ($shopconfig as $key => $value) {
                if ($shopconfig[$key]['shopid'] == $shopid ) {
                    $shoptime_config['like'] =$value['like'];
                }
            }
        }

        //分店是否与总店使用同样规划规则
        if ($shopid==1 || $shoptime_config['like']==1) {
            $item2 = ShopplanModel::getTimeConfigByStoreId($storeid,'1');
        }else{
            $item2 = ShopplanModel::getTimeConfigByStoreId($storeid,$shopid);
        }


        $id=$item2['id'];//获取分店时间配置表的id

        //获取店铺（storeid或者themeid）的所有规划信息
        $tplitem = ShopplanModel::getSpecialWorktimesListByStoreid($storeid);
        //获取店铺-分店-时间配置信息，结束


        //每周时间规划
        if(!empty($item2['workdays'])){
            $workdays=json_decode($item2['workdays'],TRUE);
        }
        //特殊日期
        if(!empty($item2['special_rules'])){
            $special_rules=json_decode($item2['special_rules'],TRUE);
        }

        //特殊虚拟数据日
        if (!empty($item2['virtual'])) {
            $virtual01=json_decode($item2['virtual'],TRUE);
            $v_totalnums=$virtual01['virtualnums'];
        }

        $p_data = array();
        //遍历$data，给每个日期：已预约数量/总可预约数量
        if (!empty($data)) {
            foreach ($data as $key => $value) {
                //获取当前日期是周几
                $week=date('w',strtotime($value));

                if ($week==1) {
                    $tplid=$workdays['week01'];
                }elseif ($week==2) {
                    $tplid=$workdays['week02'];
                }elseif ($week==3) {
                    $tplid=$workdays['week03'];
                }elseif ($week==4) {
                    $tplid=$workdays['week04'];
                }elseif ($week==5) {
                    $tplid=$workdays['week05'];
                }elseif ($week==6) {
                    $tplid=$workdays['week06'];
                }elseif ($week==0) {
                    $tplid=$workdays['week07'];
                }


                if ($tplid=='holiday') {
                    $p_data[$key]['totalnums']=0;
                    $p_data[$key]['date']=$value;
                    $p_data[$key]['planed']   =0;
                    $p_data[$key]['tplid']=0;
                }elseif ($tplid=='virtual') {
                    $p_data[$key]['totalnums']=$v_totalnums;
                    $p_data[$key]['date']=$value;
                    $p_data[$key]['planed']   =$v_totalnums;
                    $p_data[$key]['tplid']=0;
                }else{
                    $item3 = ShopplanModel::getSpecialWorktimesById($tplid);
                    $rules3 =json_decode($item3['s_work_rules'],TRUE);
                    $p_data[$key]['totalnums']=0;
                    $p_data[$key]['date']=$value;

                    if ($item3['status']!=1) {
                        $p_data[$key]['totalnums']=0;
                        $p_data[$key]['planed']   =0;
                        $p_data[$key]['tplid']=0;
                    }else{
                        if (!empty($rules3)) {
                            foreach ($rules3 as $k3 => $v3) {
                                if ($agelimit ==1 && $v3['ages_start'] <= $age && $age <=$v3['ages_end']) {
                                    $p_data[$key]['totalnums']=$p_data[$key]['totalnums']+$v3['nums'];
                                }elseif(empty($age)) {
                                    $p_data[$key]['totalnums']=$item3['totalnums'];
                                }elseif($agelimit==1 && empty($v3['ages_end'])) {
                                    $p_data[$key]['totalnums']=$item3['totalnums'];
                                }elseif($agelimit==0) {
                                    $p_data[$key]['totalnums']=$item3['totalnums'];
                                }
                            }
                        }

                        $get_item = ShopplanModel::searchUserPlaned($storeid,$shopid,$value);
                        $p_data[$key]['planed']=isset($get_item[0]['nums'])?$get_item[0]['nums']:0;
                        $p_data[$key]['tplid']=$tplid;
                    }
                }

                if(!empty($special_rules)){//规划规则
                    foreach ($special_rules as $k1 => $v1) {
                        if ($value == $v1['workdays']) {
                            $tplid=$v1['tplid'];
                            $item3 = ShopplanModel::getSpecialWorktimesById($tplid);
                            $rules3 =json_decode($item3['s_work_rules'],TRUE);
                            $p_data[$key]['totalnums']=0;
                            $p_data[$key]['date']=$value;
                            //特殊日期赋值特殊计划名称
                            $p_data[$key]['tplname'] = $item3['tplname'];

                            if ($item3['status']!=1) {
                                $p_data[$key]['totalnums']=0;
                                $p_data[$key]['planed']   =0;
                                $p_data[$key]['tplid']=0;
                            }else{

                                if (!empty($rules3)) {
                                    foreach ($rules3 as $k2 => $v2) {
                                        if ($agelimit==1 && $v2['ages_start'] <= $age && $age <=$v2['ages_end']) {
                                            $p_data[$key]['totalnums']=$p_data[$key]['totalnums']+$v2['nums'];
                                        }elseif(empty($age)) {
                                            $p_data[$key]['totalnums']=$item3['totalnums'];
                                        }elseif($agelimit==1 && empty($v2['ages_end'])) {
                                            $p_data[$key]['totalnums']=$item3['totalnums'];
                                        }elseif($agelimit==0){
                                            $p_data[$key]['totalnums']=$item3['totalnums'];
                                        }
                                    }
                                }

                                // $p_data[$key]['totalnums']=$item3['totalnums'];
                                $get_item = ShopplanModel::searchUserPlaned($storeid,$shopid,$value);
                                $p_data[$key]['planed']=isset($get_item[0]['nums'])?$get_item[0]['nums']:0;
                                $p_data[$key]['tplid']=$tplid;
                            }
                        }
                    }
                }
                //早于今天的日期，不可预约
                if ((strtotime($value) <= time() && $value != date("Y-m-d")) || (strtotime($value)<$theme['begintime'])) {
                    $p_data[$key]['totalnums']=0;
                    $p_data[$key]['date']=$value;
                    $p_data[$key]['planed']   =0;
                    $p_data[$key]['tplid']=0;
                    $p_data[$key]['is_pre']=1;
                }
                //晚于“活动最后1天”的日期，不可预约
                if (strtotime($value) > strtotime($end_date)) {
                    $p_data[$key]['totalnums']=0;
                    $p_data[$key]['date']=$value;
                    $p_data[$key]['planed']   =0;
                    $p_data[$key]['tplid']=0;
                    $p_data[$key]['is_after']=1;
                }
            }
        }

        //以上部分，直接引入整理好了的$p_data数据


         //获取当前月多少天
        $days=date('t',strtotime("{$year}-{$month_n}-1"));
        //当前一号周几
        $week=date('w',strtotime("{$year}-{$month_n}-1"));
        
        $year_end =date('Y',strtotime($end_date));//获取活动结束年
        $month_end=date('m',strtotime($end_date));//获取活动结束月

        //计算上个月
        if($month_n==1){
            $prevyear=$year-1;
            $prevmonth=12;
        }else{
            $prevyear=$year;
            $prevmonth=$month_n-1;
        }

        //计算下个月
        if($month_n==12){
            $nextyear=$year+1;
            $nextmonth=1;
        }else{
            $nextyear=$year;
            $nextmonth=$month_n+1;
        }

        //拼接输出到前端的日历表
        $ruleBtn_html="<div class=\"swiper-slide\">".PHP_EOL;
        $ruleBtn_html.="<div class=\"dataBar\">".PHP_EOL;
        $ruleBtn_html.="<div class=\"dataTime\">";
        if ($prevyear >$year_now ||  ($prevyear == $year_now && $prevmonth >= $month)){
            $ruleBtn_html.="<a onclick='changePreDate({$prevyear},{$prevmonth})'>上一月||</a>";
        }else{
            $ruleBtn_html.="没有更早月份||";
        }
        $ruleBtn_html.="<span>{$month_n}月</span>/{$year}年||";
        if ($nextyear < $year_end || ($nextyear == $year_end && $nextmonth <= $month_end)) {
            $ruleBtn_html.="<a onclick='changeNextDate({$nextyear},{$nextmonth})'>下一月</a>";
        }else{
            $ruleBtn_html.="没有更晚月份";
        }

        $ruleBtn_html.="</div>".PHP_EOL;
        $ruleBtn_html.="<div class=\"dataList\">".PHP_EOL;
        $ruleBtn_html.="<ul>".PHP_EOL;
        $ruleBtn_html.='<li class="cur"><span>周日</span></li>'.PHP_EOL;
        $ruleBtn_html.='<li class="cur"><span>周一</span></li>'.PHP_EOL;
        $ruleBtn_html.='<li class="cur"><span>周二</span></li>'.PHP_EOL;
        $ruleBtn_html.='<li class="cur"><span>周三</span></li>'.PHP_EOL;
        $ruleBtn_html.='<li class="cur"><span>周四</span></li>'.PHP_EOL;
        $ruleBtn_html.='<li class="cur"><span>周五</span></li>'.PHP_EOL;
        $ruleBtn_html.='<li class="cur"><span>周六</span></li><li style="clear:both"></li>'.PHP_EOL;

        if ($days==count($p_data)) {
            for ($i=1-$week; $i <=$days ;) {
                for ($j=0; $j < 7; $j++) {
                    if ($i>$days || $i<1) {
                        $ruleBtn_html.="<li>&nbsp;</li>".PHP_EOL;
                    }else{
                        if($p_data[$i-1]['planed'] < $p_data[$i-1]['totalnums']){

                            $ruleBtn_html.="<li class=\"cur\"><a onclick='userPlan(\"{$p_data[$i-1]['date']}\",{$p_data[$i-1]['totalnums']},{$p_data[$i-1]['planed']},\"{$p_data[$i-1]['tplid']}\")";
                            // $ruleBtn_html.=createMobileUrl("wx",array("planedid"=>$planedid,"themeid"=>$themeid,"shopid"=>$shopid,"birthday"=>$birthday,"date"=>$p_data[$i-1]['date'],"from"=>"mobile","r"=>"shopplan.getweeknav"));
                            $ruleBtn_html.="'><span>{$i}</span></a>";
                        }elseif ($year==$year_now && $month_n==$month && $day > $i ) {
                            $ruleBtn_html.="<li><span>{$i}</span>";
                        }elseif($p_data[$i-1]['totalnums'] !=0 && $p_data[$i-1]['planed'] >= $p_data[$i-1]['totalnums']){
                            $ruleBtn_html.="<li><span>{$i}</span><i>已约满</i>";
                        }elseif($p_data[$i-1]['totalnums'] ==0 && $p_data[$i-1]['tplid'] != 0 && isset($p_data[$i-1]['tplname'])){
                            $ruleBtn_html.="<li><span>{$i}</span><i style='color:grey;'>{$p_data[$i-1]['tplname']}</i>";
//                        }elseif($p_data[$i-1]['totalnums'] ==0 && $p_data[$i-1]['tplid'] != 0){
//                            $ruleBtn_html.="<li><span>{$i}</span><i style='color:grey;'>年龄限制</i>";
                        }elseif($p_data[$i-1]['is_after']==1){
                            $ruleBtn_html.="<li><span>{$i}</span><i style='color:grey;'>不可预约</i>";
                        }
                        elseif($p_data[$i-1]['is_pre']==1){
                            $ruleBtn_html.="<li><span>{$i}</span><i style='color:grey;'></i>";
                        }
                        elseif($p_data[$i-1]['totalnums']==0 && $p_data[$i-1]['is_pre'] != 1){
                            $ruleBtn_html.="<li><span>{$i}</span><i style='color:grey;'>休息日</i>";
                        }
                        $ruleBtn_html.="</li>".PHP_EOL;
                    }
                    $i++;
                }
                $ruleBtn_html.="<li style='clear:both'></li>";
            }
        }
        $ruleBtn_html.="</ul>".PHP_EOL;
        $ruleBtn_html.="</div>".PHP_EOL;
        $ruleBtn_html.="</div>".PHP_EOL;
        $ruleBtn_html.="</div>".PHP_EOL;

        $format_res = [
            'ruleBtn_html'=>$ruleBtn_html,
        ];
        return_json(0,'操作成功',$format_res);
    }
}
?>